Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter sueblue

    (@sueblue)

    I have added the following code to functions.php but it is still showing the posts by the default order (newest to oldest).

    function my_change_sort_order($query){
            if ( is_post_type_archive( 'products' ))
    		{
               $query->set( 'orderby', 'title' );
               $query->set( 'order', 'ASC' );
    		}
        }
    add_action( 'pre_get_posts', 'my_change_sort_order');

    I have hundreds of posts and the filter does a great job filtering them by category and subcategory, but they are not ordered by title.

    Plugin Author Jonathandejong

    (@jonathandejong)

    Hi Sue,

    The filter doesn’t actually have anything to do with how you choose to display the posts. So you’re on the right track BUT the conditional is_post_type_archive() does not work when you’re also filtering on taxonomies (read upon the codex) so you’ll have to extend your conditional to cover the taxonomy archives as well. I haven’t tested this but I think it should work:

    function alter_post_order( $query ) {
        if ( is_admin() || ! $query->is_main_query() )
            return;
    
        if ( is_post_type_archive( 'products' ) || is_tax(array('taxslug', 'anothertaxslug')) ) {
            $query->set( 'orderby', 'title' );
            $query->set( 'order', 'ASC' );
            return;
        }
    }
    add_action( 'pre_get_posts', 'alter_post_order', 1 );
    Thread Starter sueblue

    (@sueblue)

    Hi Jonathan,
    Thanks for your prompt answer and help.
    Code worked!

    Plugin Author Jonathandejong

    (@jonathandejong)

    No problem ?? Glad it worked out for you.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Order by Post by title’ is closed to new replies.