• Resolved babrees

    (@babrees)


    Using code below to display posts in alphabetical order, but I want to exclude categories 7 & 9. How would I do this?

    function custom_order_category( $query ) {
    	// exit out if it's the admin or it isn't the main query
    	if ( is_admin() || ! $query->is_main_query() ) {
    		return;
    	}
    	// order category archives by title in ascending order
    	if ( is_category() ) {
    		$query->set( 'order' , 'asc' );
    		$query->set( 'orderby', 'title');
    		return;
    	}
    }
    add_action( 'pre_get_posts', 'custom_order_category', 1 );
Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi,

    I would like to suggest you use ‘category__not_in’ in your query so as to exclude categories 7 & 9.

    I have tried to update your code, but not tested the code by myself please check the code below:

    function custom_order_category( $query ) {
    	// exit out if it's the admin or it isn't the main query
    	if ( is_admin() || ! $query->is_main_query() ) {
    		return;
    	}
    	// order category archives by title in ascending order
    	if ( is_category() ) {
    		$query->set( 'order' , 'asc' );
    		$query->set( 'orderby', 'title');
                    $query->set( 'category__not_in', array( 7, 9));
    
    		return;
    	}
    }
    add_action( 'pre_get_posts', 'custom_order_category', 1 );

    Hope this works for you.

    Thanks.

    Thread Starter babrees

    (@babrees)

    Thanks, but that removes all the posts in those categories.

    Thread Starter babrees

    (@babrees)

    Done it!!!! Added the is_category bit and that worked! Thanks.

    function custom_order_category( $query ) {
    	// exit out if it's the admin or it isn't the main query
    	if ( is_admin() || ! $query->is_main_query() ) {
    		return;
    	}
    	// order category archives by title in ascending order
    	if ( is_category() && ! is_category( 7,9 ) ) {
    		$query->set( 'order' , 'asc' );
    		$query->set( 'orderby', 'title');
    		return;
    	}
    }
    add_action( 'pre_get_posts', 'custom_order_category', 1 );
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Post order by title, except category # and #’ is closed to new replies.