已解决
0

我们平时使用WordPress做搜索的时候,默认的只是去查询文章的title和content,但是我在最近做一个WordPress问答主题的时候,因为很多关键的内容其实是在评论中的,所以想着是否调整一下WordPress默认的搜索功能,让其能支持对评论内容的查询,如果评论中也包含搜索关键词,也作为搜索结果输出出来,不知道哪位大神能不吝赐教啊,哈哈

1 个回答

最佳
WordPress日记
超哥
行业大佬
行业大佬
时间: 2020年11月19日

如果您的搜索使用的是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' );