php - 带有帖子和自定义字段的 Wordpress 搜索
问题描述
大家好,我目前正在 wordpress 中构建搜索功能,我可以搜索帖子类型,但在搜索与帖子类型相关的自定义字段时遇到问题。这是代码,我宁愿不使用任何搜索插件或全局变量。(除非必要)
class Search {
public function __construct() {
add_filter( 'pre_get_posts', array( $this, 'posts_filter' ) );
}
public function posts_filter( $query ) {
if ( is_admin() || ! $query->is_main_query() || ! is_search() ) {
return $query;
}
$meta_query = array(
'relation' => 'OR',
array(
'relation' => 'OR',
array(
'key' => 'book_writer',
'value' => get_search_query(),
'compare' => 'LIKE',
),
array(
'key' => 'book_isbn',
'value' => get_search_query(),
'compare' => 'LIKE',
),
),
);
$query->set('meta_query', $meta_query);
$query->set( 'post_type', 'book' );
return $query;
}
}
我不知道如何将这些自定义字段添加到 $query 中,但是像这样它只返回帖子类型“book”(如果我传递了正确的名称)并且如果我搜索 ISBN,例如搜索不'不返回任何结果。
感谢大家
解决方案
试试这个
class Search {
public function __construct() {
add_action( 'pre_get_posts', [ $this, 'posts_filter' ] );
}
public function posts_filter( $query ) {
if ( is_admin() || ! $query->is_main_query() || ! is_search() ) {
return $query;
}
$meta_query = [
'relation' => 'OR',
[
'key' => 'book_writer',
'value' => $query->query['s'],
'compare' => 'LIKE',
],
[
'key' => 'book_isbn',
'value' => $query->query['s'],
'compare' => 'LIKE',
],
];
$query->set('meta_query', $meta_query);
$query->set( 'post_type', 'book' );
}
}
从官方文档中,描述了 meta_query 的语法 https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters
推荐阅读
- javascript - document.execCommand("paste") 不起作用 - 返回 false
- android - 我的 Android Studio 偏好没有 maven repo
- macos - macOS 上 Rust 程序的类 DTrace 函数追踪
- oracle - 如何将 select 语句的结果插入记录表(关联数组)
- php - 有没有办法以他在 laravel 的最后价格获得产品
- java - Thread.start() 方法锁定了哪个对象?
- c - 如何使用 libnl 将我的设备连接到 wifi?
- javascript - 我可以在渲染函数中使用样式化组件 css`` 方法吗?
- angular - 共享同一个组件
- arrays - 无法从数组中删除不需要的项目