首先,不要使用query_posts
.
第二,你可以通过s
参数以获取大部分路径。
$program_search = \'test\';
$args = array(
\'post_type\' => \'program\',
\'s\' => $program_search,
\'meta_query\' => array(
array(
\'key\' => \'keywords\',
\'value\' => $program_search,
\'compare\' => \'LIKE\'
),
)
);
$t = new WP_Query($args);
var_dump($t->request);
那个
s
参数启动普通的搜索机制,并搜索标题和内容。如果查看生成的查询,您将看到。。。
SELECT
SQL_CALC_FOUND_ROWS
wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
WHERE 1=1
AND (((wp_posts.post_title LIKE \'%test%\') OR (wp_posts.post_content LIKE \'%test%\')))
AND (wp_posts.post_password = \'\')
AND wp_posts.post_type = \'program\'
AND (wp_posts.post_status = \'publish\')
AND ((wp_postmeta.meta_key = \'keywords\' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE \'%test%\'))
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 5
这是你最想要的。这个
LIMIT
除非另有规定,否则是在wp admin->Settings->General(wp管理->设置->常规)中设置的限制。但有一个问题。
AND ((wp_postmeta.meta_key = \'keywords\' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE \'%test%\'))
我很确定你想这样
OR ((wp_postmeta.meta_key ...
你真的很想
post_title
以及
post_content
也类似这样:
AND (
(
(wp_posts.post_title LIKE \'%test%\')
OR
(wp_posts.post_content LIKE \'%test%\')
OR
(wp_postmeta.meta_key = \'keywords\' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE \'%test%\')
)
)
WP_Query
不会这样做,所以我们必须使用一些过滤器。概念验证:
function add_join_wpse_99849($joins) {
global $wpdb;
return $joins . " INNER JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)";
}
function alter_search_wpse_99849($search,$qry) {
global $wpdb;
$add = $wpdb->prepare("({$wpdb->postmeta}.meta_key = \'keywords\' AND CAST({$wpdb->postmeta}.meta_value AS CHAR) LIKE \'%%%s%%\')",$qry->get(\'s\'));
$pat = \'|\\(\\((.+)\\)\\)|\';
$search = preg_replace($pat,\'(($1 OR \'.$add.\'))\',$search);
return $search;
}
$program_search = \'test\';
$args = array(
\'post_type\' => \'program\',
\'s\' => $program_search
);
add_filter(\'posts_join\',\'add_join_wpse_99849\');
add_filter(\'posts_search\',\'alter_search_wpse_99849\',1,2);
$t = new WP_Query($args);
remove_filter(\'posts_join\',\'add_join_wpse_99849\');
remove_filter(\'posts_search\',\'alter_search_wpse_99849\',1,2);
// dump some data
var_dump($t->request);
var_dump($t->posts);
请注意,我遗漏了
meta_query
完全重复了功能。那是为了避免麻烦
AND
从生成。
您正在应用并立即删除这些过滤器,以便它们不会干扰任何其他查询。还有其他方法可以避免筛选或其他查询。One such method is outlined here. 您还可以添加remove_filter
到add_filter
回调,让它们自动删除自己。