Wordpress order posts by post type

后端 未结 5 969
北海茫月
北海茫月 2020-12-17 04:30

I am trying to create a system which fetches post from 2 post types and i want to display the posts order by their post type. I am trying to first show the posts from one po

5条回答
  •  我在风中等你
    2020-12-17 04:42

    Order per post types with custom post type order:

    add_filter('pre_get_posts', function ($query) {
    
        if ($query->is_search && !is_admin()) :
            $query->set('post_type', [ 'cpt-1', 'cpt-2', 'post', 'cpt-3']);
        endif;
    
        return $query;
    });
    
    
    
    add_filter('posts_orderby', function ( $order ) {
    
        if ( ! is_admin() ) :
    
            if ( is_search() && is_main_query() ) :
    
                global $wpdb;
                $order = "FIELD( post_type, 'cpt-1', 'cpt-2', 'post' ), {$wpdb->posts}.post_modified DESC";      
            endif;
    
        // Disable this filter for future queries!
        remove_filter( current_filter(), __FUNCTION__);
        endif;
    
        return $order;
    });
    

提交回复
热议问题