仅按元键/元值搜索

时间:2012-08-30 作者:moraleida

这一次我就快到了。

关于函数。php我有:

function base_home_product_post_type( $query ) {

    if($query->is_search() && $_POST[\'box\'] == \'sku\') {
        $query->query_vars[\'post_type\'] = \'product\';
        $query->query_vars[\'meta_key\'] = \'sku\';
        $query->query_vars[\'meta_value\'] = $query->query_vars[\'s\'];
        return;
    }

}
add_action(\'pre_get_posts\', \'base_home_product_post_type\', 1);
它会按指示行事。在meta\\u键“sku”上搜索搜索字符串。这里的问题是,默认情况下,从WordPress返回的查询对象也包含此和查询post_titlepost_content 默认情况下:

SELECT SQL_CALC_FOUND_ROWS  whirl_2_posts.ID FROM whirl_2_posts  INNER JOIN whirl_2_postmeta ON (whirl_2_posts.ID = whirl_2_postmeta.post_id) WHERE 1=1  AND (((whirl_2_posts.post_title LIKE \'%__SEARCH_STRING__%\')  OR (whirl_2_posts.post_content LIKE \'%__SEARCH_STRING__%\')))
当我只搜索“sku”值时,我真的不想这样,所以我尝试使用posts_where 还有一些非常难看的正则表达式,如以下(警告、黑客和马车):

function get_rid_of_titles($search) {
    if(is_search() && $_POST[\'box\'] == \'sku\') {
    $search = preg_filter(\'|AND\\s\\({3}\\w*\\.post_title\\sLIKE\\s\\\'\\%[^%]*\\%\\\'\\) OR \\(\\w*\\.post_content\\sLIKE\\s\\\'\\%[^%]*\\%\\\'\\){3}\\s|\', \'\', $search);
    }
    return $search;
}
add_filter(\'posts_where\',\'get_rid_of_titles\');
但运气不好。在这种情况下,谁能告诉我如何在线搜索自定义值?

SOLUTION

多亏了下面的@kaiser,我才得以实现这一目标:

function get_rid_of_titles($search) {

    if(is_search() && $_POST[\'box\'] == \'sku\') {

          $sku = $_POST[\'s\'];          // get search string
          $needle = "LIKE \'%$sku%\'";   // search only for LIKE \'%_SEARCH_STRING_%\'. This is a multisite environment, so involving table names directly is a bad idea
          $replace = "LIKE \'%\'";       // replace it with SQL Wildcard so any title and any content are welcome
          $count = 2;                  // only the first 2 occurrencies which happen to be post_title and post_content
          return str_replace($needle,$replace,$search, $count);

    }
}
add_filter(\'posts_where\',\'get_rid_of_titles\');

1 个回复
最合适的回答,由SO网友:kaiser 整理而成

您可以做两件事:

A) 将搜索替换为只搜索Posteta表的SQL查询(由于没有JOIN 参与-稍后显示结果时,您可以通过其ID获取帖子)。

B) 紧接着拆分字符串WHERE 1=1 然后去掉后面的部分。您可以使用return str_replace( $query_part_below, \'\', $search );.

 AND (
    (whirl_2_posts.post_title LIKE \'%__SEARCH_STRING__%\')  
    OR (whirl_2_posts.post_content LIKE \'%__SEARCH_STRING__%\')
)
确保您$wpdb->prepare() 在把它推回之前。

结束