• Resolved Fery Rohrer

    (@ferylee)


    Hi,
    I have this beautiful code that prints the list of the categories which the post is assign to. I can exclude one category but now I need to exclude more than one… I try to put it in a array but somehow I don’t know what I’m doing wrong.

    <div class="cat_tags">
    <?php
    $categories = get_the_category();
    $excluded_cat = '1';
    $separator = ' / ';
    $output = '';
    if($categories){
    	foreach($categories as $category) {
    		if (
    			$category->cat_ID != $excluded_cat
    		)
    			$output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
    	}
    	echo trim($output, $separator);
    }
    ?>
    </div>

    Thanks for your help,
    Fery

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Go ahead and make $excluded_cat an array:
    $excluded_cat = array( 1, 3, 7,);

    Then instead of checking if $category->cat_ID != $excluded_cat, use the in_array() function to check if there’s not any match:
    ! in_array( $category->cat_ID, $excluded_cat )
    Don’t forget the NOT operator ! so you are checking if the ID is not in the array.

    Thread Starter Fery Rohrer

    (@ferylee)

    Yes! Now it works, thank you so much 🙂

    Here the working code in case someone would like to reuse it:

    <div class="cat_tags">
    <?php
    $categories = get_the_category();
    $excluded_cat = array( 1,2,18 );
    $separator = ' / ';
    $output = '';
    if($categories){
    	foreach($categories as $category) {
    		if (
    			! in_array( $category->cat_ID, $excluded_cat )
    		)
    			$output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
    	}
    	echo trim($output, $separator);
    }
    ?>
    </div>

    Thanks again!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Category tags, exclude more than one category?’ is closed to new replies.