搜索热词

WordPress中文社区 > 帖子 > > 如何让WordPress的搜索在搜索的时候也支持去查询文章的评论中是否包含搜索关键词?

如何让WordPress的搜索在搜索的时候也支持去查询文章的评论中是否包含搜索关键词?

已解决

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

发布于11月17日 被浏览 1,201 次
点赞 收藏 打赏 分享

    1 个回答

  1. 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' );