• The following code sorts all my custom post types and everything else — including in admin — in alphabetical order. Yay. Except I would like to exclude only “blog” posts from behaving this way.

    function modify_query_order( $query ) {
            $query->set( 'orderby', 'title' );
            $query->set( 'order', 'ASC' );
    }
    add_action( 'pre_get_posts', 'modify_query_order' );

    I’m trying things with get_post_type( 'post' ) but can’t seem to get it going.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You can use the following code to achieve the purpose

    function modify_query_order( $query ){
    if ( $query->query[‘post_type’] != ‘post’ ) {
    $query->set( ‘orderby’, ‘title’ );
    $query->set( ‘order’, ‘ASC’ );
    }
    }
    add_action(‘pre_get_posts’,’modify_query_order’);

    Here is a reference link which will be helpful to understand and customize the solution.

    Thread Starter raskull

    (@raskull)

    Hm, interestingly, this does exclude blog posts in admin from going alphabetical, but does not exclude “the page for posts” on the front end. Those are still going alphabetical…

    Thread Starter raskull

    (@raskull)

    Well, I’m back here again to see if I can find an adventurous soul who can solve this mystery. The below code works nearly perfectly. It is supposed to sort alphabetically all posts of every type (both in admin and on the front end), except those posts that are blog posts.

    But this is what actually happens: Blog posts in admin remain in default (date) sort as I would expect for having excluding them. But blog posts on the front end are sorting alphabetically, even though they have been excluded from the sort.

    What’s up?

    function modify_query_order( $query ){
        if( 'post' != $query->get('post_type') ){
                $query->set('orderby','title');
                $query->set('order','ASC');
        }
    }
    add_action('pre_get_posts','modify_query_order');
    Thread Starter raskull

    (@raskull)

    Me did it. I excluded “the page for posts.” The answer is often found in the question.

    function modify_query_order( $query ){
        if( 'post' != $query->get('post_type') && !is_home() ){
                $query->set('orderby','title');
                $query->set('order','ASC');
        }
    }
    add_action('pre_get_posts','modify_query_order');
Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘sorting posts with pre_get_posts in functions.php’ is closed to new replies.