按post_types分类的WordPress查询组

问题描述 投票:0回答:1

是否可以按帖子类型订购或分组WP_Query?

我正在搜索结果页面,我想要的是示例:

PAGES:

  • 链接1

  • 链接2

  • 链接3

POSTS

  • 链接1
  • 链接2
  • 链接3

自定义帖子类型:

  • 链接1
  • 链接2
  • 链接3
wordpress loops search
1个回答
1
投票
add_filter( 'posts_orderby', 'filter__posts_orderby', 10, 2 );

function filter__posts_orderby( $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' 
                 WHEN {$wpdb->prefix}posts.post_type = 'your_custom_post_type' THEN '3' 
                 WHEN {$wpdb->prefix}posts.post_type = 'your_custom_post_type' THEN '4' 
            ELSE {$wpdb->prefix}posts.post_type END ASC, 
            {$wpdb->prefix}posts.post_title ASC";
    endif;
    return $orderby;
}

也许这会帮助您!

下面是在搜索结果中添加自定义帖子类型的代码:

add_action( 'pre_get_posts','action__pre_get_posts' );

function action__pre_get_posts($wp_query){
  if ( !is_admin() && is_main_query() && is_search() ){
    $wp_query->set( 'post_type'=>array('post','your_custom_post_type','page' ) );
  }
}

也将此代码放在活动主题的functions.php文件中。

© www.soinside.com 2019 - 2024. All rights reserved.