WordPress搜索结果页面首先发布

时间:2018-09-26 00:59:12

标签: php wordpress search

我试图为WP默认搜索添加一个功能,我想先将其结果添加到鞋子页面项目上,然后发布项目,但目前尚不可行。 我没有使用任何插件进行搜索。

这是我的代码(在function.php中):

第一个

<?php 
function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', array('page', 'post'));

};
return $query;
};
add_filter('pre_get_posts', 'filter_search');
?>

我尝试过的第二个

<?php
function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', 
       array(
       'post_type'=>'page', 
       'orderby' => 'title',
       'order'   => 'DESC',
       )
       );
} else {
$query->set('post_type', 
       array(
       'post_type'=>'post', 
       'order'   => 'DESC',
       )
       );
};
return $query;
add_filter('pre_get_posts', 'filter_search');
?>

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以尝试使用SQL CASE表达式

add_filter( 'posts_orderby', 'order_search_by_posttype', 10, 2 );
function order_search_by_posttype( $orderby, $wp_query ){
    if( ! $wp_query->is_admin && $wp_query->is_search ) :
        global $wpdb;
        $orderby =
            "
            CASE WHEN {$wpdb->prefix}posts.post_type = 'page' THEN '1' 
                 WHEN {$wpdb->prefix}posts.post_type = 'post' THEN '2' 
            ELSE {$wpdb->prefix}posts.post_type END ASC, 
            {$wpdb->prefix}posts.post_title ASC";
    endif;
    return $orderby;
}

我在这里找到了此解决方案,https://wordpress.stackexchange.com/questions/177650/sort-search-results-by-post-type/177653#177653

相关问题