1

I want to add the currenty category to the body class.

How do I need to modify my current code, to add also the current category as a body class to the is_singular( 'knowledgebase' ) section?

My current code looks like this:

function add_body_class( $classes ) {

    global $pakb;

    if( is_page( $pakb->get( 'kb_page' ) ) && ! is_null(  $pakb->get( 'kb_page' ) ) ) {
        $classes[] = 'pakb-main';
    } elseif ( is_tax( 'knowledgebase_category' ) ) {
        $classes[] = 'pakb-category';
    } elseif ( is_singular( 'knowledgebase' ) ) {
        $classes[] = 'pakb-single';
    }

    return $classes;

}

2 Answers 2

1

This late in the process you should be able to rely on context set up, even outside of loop.

On top of my head something like this should work:

$categories = wp_get_post_categories( get_the_ID(), [ 'fields' => 'names' ] );
2
  • Thanks for your reply! I do not know exectly what you mean with on top of my head. Isn't there an easy way to edit my current code and expand it?
    – JGeer
    Commented Aug 23, 2016 at 12:36
  • I have shown you how to retrieve categories in the context you provided, rest is realm of basic PHP. Complete solution for custom requirements is not something that you will typically get at this site, we focus on learning and knowledge aspects of development.
    – Rarst
    Commented Aug 23, 2016 at 12:42
1

Here I don't understand what is global $pakb.

But extending to Rarst answer :

add_filter('body_class', 'add_body_class');

function add_body_class($classes) {
    global $pakb;
    global $post;

    if( is_page( $pakb->get( 'kb_page' ) ) && ! is_null(  $pakb->get( 'kb_page' ) ) ) {
        $classes[] = 'pakb-main';
    } elseif ( is_singular( 'knowledgebase' ) ) {
        // getting all category name related to this post
        $categories = wp_get_post_categories( $post->ID, [ 'fields' => 'names' ] );

        $classes[] = $categories;
    }

    return $classes;

return $classes;
}
5
  • Thanks! I tried that, but that does not seem to work.
    – JGeer
    Commented Aug 23, 2016 at 12:55
  • It will add the WP default category name to your body class for knowledgebase post type. Hope this is clear.
    – Aftab
    Commented Aug 23, 2016 at 13:31
  • I do know that, but that does break down the entire page. So the code does not work/is not correct.
    – JGeer
    Commented Aug 23, 2016 at 13:56
  • what is the error it is displaying?Have your turned on your debug mode
    – Aftab
    Commented Aug 23, 2016 at 14:04
  • Hi, I get the following error: Parse error: syntax error, unexpected 'add_filter' (T_STRING), expecting function (T_FUNCTION) in /file.php on line 84
    – JGeer
    Commented Aug 24, 2016 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.