这个问题是a question I recently asked.
我已经实现了似乎是唯一的解决方案,而且似乎奏效了(耶!)。我只需要验证一下:
这是修改查询以匹配(post_title OR post_content
或所需的任何其他元字段这不会影响其他与搜索无关的查询。我认为,下面使用的regex通常只用于搜索,但它与核心或插件中的其他功能相匹配的可能性有多大。我意识到插件可能会发生任何事情,但我特别担心WP核心中的冲突我考虑过在posts_where
过滤器,但认为最好依靠修改$query
尽可能多地限制直接修改WHERE
. 这是一个合理的选择吗在任何情况下,以下是用于修改WHERE
:
function st_posts_where( $where ){
if( !is_admin() ){
global $wpdb;
$ptn = "/(\\s*AND \\(\\(\\({$wpdb->prefix}posts.post_title LIKE \'%.*%\'\\)\\s+OR\\s+\\(".
"{$wpdb->prefix}posts.post_content LIKE \'%.*%\'\\)\\)\\)\\s+)AND(.*)/";
$where = preg_replace( $ptn, "$1OR$2", $where );
}
return $where;
}
add_filter( \'posts_where\' , \'st_posts_where\' );
此外,以下是
original question 正在寻址,它仍然与上面的一个一起使用。
function st_search_all( $query ) {
if( !is_admin() && $query->is_search ) {
$query->set( \'post_type\', array( \'page\', \'attachment\' ) );
$query->set( \'post_status\', \'inherit\' );
$query->set( \'meta_query\', array(
\'relation\' => \'OR\',
array(
\'key\' => \'_st_plaintext\',
\'value\' => $query->get(\'s\'),
\'compare\' => \'LIKE\'
),
array(
\'key\' => \'Training Classes\',
\'value\' => $query->get(\'s\'),
\'compare\' => \'LIKE\'
),
array(
\'key\' => \'External Content\',
\'value\' => $query->get(\'s\'),
\'compare\' => \'LIKE\'
)
) );
}
return $query;
}
add_filter( \'pre_get_posts\', \'st_search_all\' );
所有这些结合在一起会产生以下查询结果,从而获得所需的结果:
AND (((dev_posts.post_title LIKE \'%sbir%\')
OR (dev_posts.post_content LIKE \'%sbir%\')))
OR dev_posts.post_type IN (\'page\', \'attachment\')
AND (dev_posts.post_status = \'inherit\')
AND (
(dev_postmeta.meta_key = \'_st_plaintext\'
AND CAST(dev_postmeta.meta_value AS CHAR) LIKE \'%sbir%\')
OR (mt1.meta_key = \'Training Classes\'
AND CAST(mt1.meta_value AS CHAR) LIKE \'%sbir%\')
OR (mt2.meta_key = \'External Content\'
AND CAST(mt2.meta_value AS CHAR) LIKE \'%sbir%\'))