When creating a custom WP theme, I try to add additional classes to the body tag if the user goes to the bonus or news page ( example.com/bonuses/ example.com/news/ ), (the page_bonuses and page_news , respectively), but for some reason nothing not happening.

 function my_body_class_filter($classes) { if( is_single('bonuses') ){ $classes[] = 'page_bonuses'; }elseif (is_single('news') ){ $classes[] = 'page_news'; } return $classes; }; <body class="body" <?php body_class(add_filter('body_class', 'my_body_class_filter')); > 

What is wrong I prescribe in conditional tags?

enter image description here

    1 answer 1

    The call is incorrectly built.

    In functions.php should be

     function my_body_class_filter( $classes ) { global $post; if ( $post ) { $classes[] = $post->post_name; } return $classes; } add_filter( 'body_class', 'my_body_class_filter' ); 

    In header.php

     <body <?php body_class(); ?>> 

    PS is_single('slug') does not work for pages. Therefore, in my code, the name of the post (slug) is added to the classes. This works for any type of post, including pages.

    • I did as it is written, there are no changes yet. So it brings to body class = "body customize-support" - Andrey Zirka
    • I did not notice that you have a page, not a record. Corrected the answer. - KAGG Design
    • Um, now, of course, everything is poured out prntscr.com/jtn3pf But I don’t need so much, and for some reason it ate the .body class from the body tag. I would only have two pages to display these extra classes - Andrey Zirka
    • First, you need all this. Many plugins are based on this. And you just don’t need the body class, unless you use it yourself in layout, which is strange. But if you really need to, add one line to the filter before return: $classes[] = 'body'; - KAGG Design
    • In fact, I don’t need such a canvas from the prntscr.com/jtyv6l classes. Besides, I don’t know how to make the necessary css modification for me if the URL of the page is for example example.com/news/razvedenie-homyakov (I’ll remind you that I still need to add the page_news class to the body) I just can’t bind to the desired class - Andrey Zirka