xzen xzen
asked 7 years ago

Hello,

how can I add body class based on dwqa-question_category?

I tried something like this but it doesn´t work

function section_id_class( $classes ) {
global $post;

$section_terms = get_the_terms( $post->ID, 'dwqa-question_category' );
if ( $section_terms && ! is_wp_error( $section_terms ) ) {
    foreach ($section_terms as $term) {
        $classes[] = 'section-' . $term->slug;
    }
}

return $classes;

}
add_filter( ‘body_class’, ‘section_id_class’ );

Thank´s

xzen
replied 7 years ago

This code works but only when I in detail page = question detail. I need add body class when I click on the question category in the list of questions.

nobita
replied 7 years ago

Well it’s not work because the categories there are made by Ajax-call each time you reload page and i think it’ll run after the add class function init. to add class there i think you need to write some javascript 😀

2 Answers
DominicStaff
answered 7 years ago

Hi,
To
You can add the following code to the functions.php file of your site:

function section_id_class( $classes ) {
if ( is_tax( 'dwqa-question-category') ) {
   $classes[] = 'your class';
}
return $classes;
}
add_filter( ‘body_class’, ‘section_id_class’ );

Hope this helps !

xzen
replied 7 years ago

It doesn´t work, but I need different body classes (based on slugs) for every question´s categories.

Allen
answered 7 years ago

Well , instead of using add_filter body_class( because you can’t use add_filter body classin this situation, it need the page to reload to work ) , you need to use js to put class to the what section you want to have that class:

first, you need to create a javascript file in theme folder and enqueue it to the theme, and then
you can use these code

jQuery(function($){
    $('.cat-item').live('click', function(e){
     var category_id = $(this).attr('data-cat');
     var body_class = $(this).find('a').text();
     body_class = string.replace(/[_\W]+/g, "-")
     body_class = string.toLowerCase();

        // Use jquery to push the class to where you want here ......
        });
});
Powered by DW Question & Answer Pro