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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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