Gurdt
Gurdt

Reputation: 181

WordPress Query group by post_types

Is it possible to order or group WP_Query by post types?

I'm making a search result page and what i want is example:

PAGES:

POSTS

Custom Post type:

Upvotes: 0

Views: 826

Answers (1)

Parthavi Patel
Parthavi Patel

Reputation: 767

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;
}

May be this will help you !

And Below is the code to Add your Custom Post Type in Search Result :

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' ) );
  }
}

Also Place this code in your functions.php file of active theme.

Upvotes: 1

Related Questions