function display_class_category() {
global $post;
// Make sure we are using the correct post in the loop
setup_postdata( $post );
$target_categories = array( 'bread', 'cake', 'brownie' );
$categories = get_the_category( $post->ID );
$output = '';
if ( $categories ) {
foreach ( $categories as $category ) {
if ( in_array( $category->slug, $target_categories ) ) {
$category_link = get_category_link( $category->term_id );
$output .= '<div class="link-cat">
<a href="' . esc_url( $category_link ) . '">' . esc_html( $category->name ) . '</a>
</div>';
}
}
}
wp_reset_postdata();
return $output;
}
add_shortcode( 'class_category', 'display_class_category' );
setup_postdata( $post ) ensures that WordPress functions like has_category() or get_the_category() reference the current post in the loop — not a leftover global value.
No return inside the loop — so you can correctly build $output for each category.
wp_reset_postdata() cleans up after the shortcode so it doesn’t mess with the rest of the loop.
<?php while ( have_posts() ) : the_post(); ?>
<h2><?php the_title(); ?></h2>
[class_category]
<?php endwhile; ?>
Now each post in your archive should show the correct linked category (bread, cake, or brownie) according to its own category.
Would you like it to show only the first matching category, or all matching ones (if a post has multiple from that list)?