• I’m trying to exclude a category and all it’s children (50 or so) from the main blog and feed. What I have seems to be working. But I thought I’d post it here in case I’ve done something wrong and it’s casuing trouble I haven’t noticed. I’m sure there’s a much more elegant solution but here it is:

    function exclude_category( $query ) {
        if ( $query->is_home() && $query->is_main_query() || $query->is_feed() ) {
    		$args = array('parent' => '4', 'orderby' => 'id');
    		$terms = get_terms( 'category', $args );
    		$noshow = '-4';
    		foreach( $terms as $term ){
      			$noshow = $noshow . ',-' . $term->term_id;
    		}
            $query->set( 'cat', $noshow );
        }
    }
    add_action( 'pre_get_posts', 'exclude_category' );

    I guess my questions are:

    1. is it okay to do a loop inside that function? I would imagine people usually do an array.

    2. it only works if the $noshow variable doesn’t have quotes around it, yet if I was just putting in a list of category id’s I think it would have to be in quotes to work.

    Sorry for the basic question I just want to understand it better.
    Thanks

  • The topic ‘Exclude child categories using pre_get_posts’ is closed to new replies.