• zigojacko

    (@zigojacko)


    I’m currently displaying a class on post items like cat-category_nicename (i.e. cat-press) using the below:-

    $categories = get_the_category($post->ID);
    foreach( $categories as $category ) {
        // Category Class
        $cat_class = 'cat-' . $category->category_nicename;
    }

    But on custom post types, has_category returns false and with the above, a class is output (the same one for all custom post types of a category – which it doesn’t belong to).

    How can I only display $cat_class if the post belongs to a category?

    I might be worth noting that I am currently display $cat_class in post_class currently like below:-

    post_class("item mix $wrapper_class $cat_class", $post->ID );

Viewing 1 replies (of 1 total)
  • Hi,

    You could do it a little differently like this:

    function jp_custom_post_classes( $classes ) {
        global $post;
        if( 'post' != get_post_type( $post->ID ) ) {
            return $classes;
        }
    
        foreach ( ( get_the_category( $post->ID ) ) as $category ) {
            $classes[] = 'cat-' . $category->category_nicename;
        }
        return $classes;
    }
    add_filter( 'post_class', 'jp_custom_post_classes' );

    You’d want that in a custom plugin or the theme’s functions.php file.

Viewing 1 replies (of 1 total)
  • The topic ‘Getting cat-category_nicename as class only if has_category’ is closed to new replies.