在我的插件代码中,我想执行一个WP_Query
(或类似的),它返回与给定查询字符串匹配的所有帖子,就好像用户在WordPress搜索表单中键入了相同的字符串一样。也许我只是太密集了,但我似乎找不到这样做的方法。我希望WP_Query
有一个特殊的参数,比如matching
,但我看不到任何证据。
我会开始浏览WordPress的代码库,看看它是如何在内部完成的,如果我找到了,我会在这里发布答案。我只是觉得可能有人会马上知道。
将查询变量"s"与搜索词一起传递给WP_Query
将按搜索词过滤发布结果:
$query_args = array( 's' => 'disquiet' );
$query = new WP_Query( $query_args );
此查询生成的相应SQL WHERE
子句如下所示:
AND (((wp_posts.post_title LIKE '%disquiet%') OR (wp_posts.post_content LIKE '%disquiet%')))
默认搜索包括如上所示的通配符,这很可能是您要查找的。如果您想要精确的搜索,还可以传递"exact" => true
的查询变量。
有关详细信息,请参阅wp includes/query.php中WP_Query
的get_posts
方法。
我在插件中使用这个:
$query = new WP_Query(array(
'post_type' => 'any',
'suppress_filters' => TRUE,
'posts_per_page' => '-1'
));
foreach ($query->posts as $post) {
// ...
}
如果要使用自定义帖子类型,则需要post_type
。如果您需要分析内容,suppress_filters
将阻止其格式化。posts_per_page
将返回所有帖子,而不是默认的每页帖子。
类似的东西?
// Check the query variable is available
if(!$wp_query) global $wp_query; // If not, global it so it can be read from
// Your custom args
$args = array( 'the_title' => $search_term );
// Merge the custom args with any for the query already
$args = array_merge( $args , $wp_query->query );
// Now do the query
query_posts( $args );
或者你可以试试这个:
$query = array (
'the_title' => $search_term
);
$queryObject = new WP_Query($query);
// The Loop...
我相信你正在寻找的是这个compare
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'LIKE'
)
)
);
来自wordpress文档
compare (string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. Default value is '='.
这是一种更简单、更容易的搜索方法:
$query = "
SELECT *
FROM $wpdb->posts
WHERE $wpdb->posts.post_title LIKE '$param2%'
AND $wpdb->posts.post_type = 'wp_exposants'
ORDER BY $wpdb->posts.post_title ";
$wpdb->get_results($query);