• Hello,

    I try to customize my archive with the category “9”.

    I use this code in my functions.php

    function archive_ausblick_order( $query ) {
    	if ( !is_admin() && is_category( '9' ) && $query->is_main_query() ) {
    		$query->set( 'meta_key', 'my_meta_box_dateBegin' );
    		$query->set( 'orderby', 'meta_value_date' );
    		$query->set( 'order', 'DESC' );
    		}
    }
    add_action( 'pre_get_posts', 'archive_ausblick_order' );

    I only want the FRONTEND, ONLY IF CATEGORY 9 and ONLY THE MAIN QUERY.

    But now all my archives are ordered like this. How can I make this function only take action if the user calls category(archive) 9?

    Thanks,
    Denis

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter DenisCGN

    (@deniscgn)

    It seems to work with:

    function archive_ausblick_order( $query ) {
    	if ( is_category( 9 ) ) {
    	if ( !is_admin() && $query->is_main_query() ) {
    		$query->set( 'meta_key', 'my_meta_box_dateBegin' );
    		$query->set( 'orderby', 'meta_value_num' );
    		$query->set( 'order', 'DESC' );
    		}
    }
    }
    add_action( 'pre_get_posts', 'archive_ausblick_order' );

    Can someone please check if this code is correct, or is there a better way to do this query customization?

    Cheers,
    Denis

    Moderator bcworkz

    (@bcworkz)

    Yes, that’s fine. TBH, I’m not sure why the first version didn’t properly restrict the ordering. Using a string instead of integer shouldn’t make a difference here, nor should a separate if() statement. Since it’s now working, let’s not try to fix it ??

    Though you might consider using $query->is_category( 9 ). It amounts to the same thing as is_category( 9 ), but it’s a little more “honest”.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Pre_Get_Posts – only Category 9’ is closed to new replies.