我需要修改或创建一个WP_Query
,它将在帖子标题或自定义字段(称为“my_field”)中搜索搜索词。
我已经阅读并尝试了几个小时,但我马上又回到了这段代码(如下),唉,它只在“my_field”中搜索,并且没有考虑 post_title
。
function my_pre_get_posts_2( $query ) {
if ( is_admin() && $query->is_main_query() && $query->query['post_type'] === 'post' && isset($query->query['s']) ) {
$search_word = $query->query['s'];
$args = array(
//'s' => $search_word, //If I include this line, the WP query seems to AND post_title and my_field. If I comment out this line, the WP query only searches in my_field. (I need WP to OR post_title and my_field.)
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'my_field',
'value' => $search_word,
'compare' => 'IN'
),
array(
'key' => 'post_title',
'value' => $search_word,
'compare' => 'IN',
)
)
);
//$query = new WP_Query( $args ); //Need to modify the existing WP_Query
$query->init();
$query->parse_query($args);
}
}
add_action( 'pre_get_posts', 'my_pre_get_posts_2' );
我需要这样做的原因是因为我需要修改“所有帖子”(管理)页面中“搜索帖子”按钮的行为,以便管理员用户搜索任何内容,都会返回帖子具有匹配的帖子标题或 my_field 值。
最佳答案
为了进行 OR 搜索,我尝试合并两个单独的 WP_Query 结果,如下所示 - https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s - 在吉多的回答中。但这并不是一个很好的解决方案,并且导致了不稳定的行为。
我发现的正确解决方案是使用 WP 自定义查询修改查询,如代码所示(需要一些修改) - http://codex.wordpress.org/Custom_Queries .
关于wordpress - 如何创建/修改 WP_Query 以在帖子标题或自定义字段中搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20847597/