我们平时使用WordPress做搜索的时候,默认的只是去查询文章的title和content,但是我在最近做一个WordPress问答主题的时候,因为很多关键的内容其实是在评论中的,所以想着是否调整一下WordPress默认的搜索功能,让其能支持对评论内容的查询,如果评论中也包含搜索关键词,也作为搜索结果输出出来
如果您的搜索使用的是WordPress默认的搜索的话,可以把下面的代码放到您的functions.php中来实现,但是可能对于自定义搜索不起作用。
/**
* WordPress搜索文章支持查询评论
* https://www.wpshequ.cn
*/
function sort_by_sticky( $query ) {
if($query->is_search && !empty($query->query['paged'])){
$search = htmlspecialchars($query->query['s']);
global $wpdb;
$querystr = "
select $wpdb->posts.ID
from $wpdb->posts
left join $wpdb->comments
on $wpdb->comments.comment_post_ID = $wpdb->posts.ID
where $wpdb->posts.post_content like \"%$search%\"
or $wpdb->comments.comment_content like \"%$search%\"
or $wpdb->posts.post_title like \"%$search%\"
or $wpdb->comments.comment_author like \"%$search%\"
group by $wpdb->posts.ID
";
$match_posts = $wpdb->get_results($querystr, OBJECT);
$query->set('s', '');
$match_post_ids = array();
foreach($match_posts as $match_post){
$match_post_ids[] = $match_post->ID;
}
$query->set('post__in', $match_post_ids);
}
}
add_action( 'pre_get_posts', 'sort_by_sticky' );
© 版权声明
免责声明:本网站所收集的部分公开资料来源于互联网,由网友自主投稿和发布、编辑整理上传,对此类文章本站仅提供交流平台,不为其版权负责,如果您发现网站上有侵犯您的知识产权的作品,请与我们取得联系,我们会及时修改或删除。
THE END
喜欢就支持以下吧