/**
* 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' );
1 个回答
如果您的搜索使用的是WordPress默认的搜索的话,可以把下面的代码放到您的functions.php中来实现,但是可能对于自定义搜索不起作用。