0

I want to display my custom post type "portfolio" in alphabetical order and I got it working fine with this code:

add_filter("posts_orderby", "my_orderby_filter", 10, 2);

function my_orderby_filter($orderby, &$query){
    global $wpdb;
    //figure out whether you want to change the order
    if (get_query_var("post_type") == "portfolio") {
         return "$wpdb->posts.post_title ASC";
    }
    return $orderby;
    }

Unfortunately it affects also normal posts order list. I don't know why. How may I fix this? Thank you

1 Answer 1

2

Try using $query->get() instead of get_query_var().

function my_orderby_filter($orderby, &$query){
    global $wpdb;
    //figure out whether you want to change the order
    if ($query->get("post_type") == "portfolio") {
         return "$wpdb->posts.post_title ASC";
    }
    return $orderby;
    }

Alternatively, you can use this one, which filters the query via the pre_get_posts hook.

add_action( 'pre_get_posts', 'my_orderby_filter2' );
function my_orderby_filter2( $query ) {
    if ( 'portfolio' === $query->get( 'post_type' ) ) {
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
    }
}
1
  • 1
    Thanks, this was useful. To do this for several post types, I used $post_types = array( 'different', 'post', 'types' ); then if( in_array( $query->get('post_type'), $post_types ) for my conditional. Commented Dec 16, 2019 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.