这一次我就快到了。
关于函数。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_title
和
post_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\');