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

admin2025-06-04  44

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

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

Share Improve this question edited Jan 8, 2019 at 21:45 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Jan 8, 2019 at 19:44 yazukyazuk 851 silver badge5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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 );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749030858a315773.html

最新回复(0)