How to specify which category of the post to use in case of multiple categories

In my theme, to display the featured post I have to add an extra category “featured”. Now I have articles showing featured in the url instead of the main category.
Any help please?
Thanls

1 Answer
1

It all depends, how these categories are displayed in your theme.

If it’s done nicely and with proper use of WP template tags, then that list comes from get_the_category() function (all other functions are using this one).

And at the end of that function you can find

return apply_filters( 'get_the_categories', $categories, $id );

So it’s great news, because it means, that you can write your own filter and remove given category from the lists:

function prefix_remove_featured_category_from_post_categories_list( $categories, $id ) {
    // do whatever you want with $categories list
    // for example remove some category from the list
    $categories_to_remove = array(
        'cat-slug-a',
        'cat-slug-b'
    ); // Array of categories slug to be remove. Put your slugs in here

    foreach ( $categories as $index => $single_cat ) {

        if ( in_array( $single_cat->slug, $categories_to_remove ) ) {
            unset( $categories[ $index ] ); // Remove the category.
        }
    }

    return $categories;
}
add_filter( 'get_the_categories', 'prefix_remove_featured_category_from_post_categories_list', 10, 2 );

Leave a Comment