Hello, I use the following code to show what categories the post is in, this is in my single.php.
For example this code outputs 'Entertainment, Featured News, Gaming'
I want to exclude 'Featured News' from this list, this is category ID=35.
<?php
$categories = get_the_category();
$separator = ', ';
$output = '';
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
} ?>
<?php } ?>
Arnav Joy answers:
Hello Ross,
Good to see you here again!
Please check my code below for the work:
<?php
$categories = get_the_category();
$separator = ', ';
$output = '';
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
if( $category->term_id == 35 ) continue;
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
} ?>
<?php } ?>
Ross Gosling comments:
Thanks Arnav, this worked perfectly.
Arnav Joy comments:
glad to know :)
Hariprasad Vijayan answers:
Hi there,
Try the following code
<?php
$categories = get_the_category();
$separator = ', ';
$output = '';
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
if($category->term_id == 35){ // Change the id if you need to exclude different category
continue;
}
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
} ?>
<?php } ?>