Advanced WordPress - How to Add a Category Class to Body Tag & jQuery Hide Show - Code By MavenBoys

Latest

Web Development & Blogging Tips/Tricks from 0 Level to Pro Level.

BANNER 728X90

Thursday, 10 October 2019

Advanced WordPress - How to Add a Category Class to Body Tag & jQuery Hide Show


WordPress - How to Add a Category Class to Body Tag & jQuery Hide Show


We the developers love to show the content on different conditions according to needs. Here, We will show you how to add a current category to the current post. Then We will hide/show a div on which category of post is related to.

So the very first step is to add the category class to WordPress body tag, to do this add a filter with body_class



add_filter('body_class','cmb_add_cat_to_post',10,2);
function cmb_add_cat_to_post($classes, $class) {
if (is_single() ) {
global $post;
// get_the_category($post->ID) will return the current category posts
//cmb is my prefix, you can change it to your own.
foreach((get_the_category($post->ID)) as $category) {
$classes[] = 'cmb-'.$category->category_nicename;
}
}
return $classes;
}

It will add the class to the body tag and then we will hide/show the div on the category based in the post.
Now

jQuery(document).ready(function(){
// Now check if body tag has class with jQuery
// replace the cmb-postcategory with your post category
if(jQuery('body').hasClass('cmb-postcategory'){
jQuery('div.hideyourdiv').hide(); // hideyourdiv will be your div class to hide that div
jQuery('div.showyourdiv').show(); // showyourdiv will be your div class to show that div
}
});

That's it. If anything confuses, just comment me here or follow me on facebook, twitter, Instagram or WhatsApp.
If it helps you then you can help others by sharing it and supporting me. Thanks

1 comment:

  1. I feel really happy to have seen your webpage and look forward to so many more entertaining times reading here. Thanks once more for all the details. Cheap Kratom

    ReplyDelete