{Name (First):7.3} requested the following code from my WordPress AI Code Generator.
add class to body if custom post type has a particular custom taxonomy
The robot generated the following code:
Below is an example of a code snippet that does as requested by adding a class to the body if a custom taxonomy is associated with a custom post type. In this case, we're assuming that the custom taxonomy is 'special_taxonomy' and the custom post type is 'custom_type'. We also made sure the function is prefixed with 'nm_add'.
“`php
function nm_add_taxonomy_class($classes) {
// your custom post type
$custom_type = 'custom_type';
// your custom taxonomy
$custom_taxonomy = 'special_taxonomy';
if( is_singular($custom_type) ) {
global $post;
$terms = get_the_terms($post->ID, $custom_taxonomy);
if ($terms) {
foreach ($terms as $term) {
$classes[] = $term->slug;
}
}
}
return $classes;
}
add_filter('body_class', 'nm_add_taxonomy_class');
“`
Let's break down this code:
– The nm_add_taxonomy_class function uses the body_class filter to add the nl_add prefix to the body class.
– It checks if the current post is of the 'custom_type' post type. If so, it gets the terms (taxonomy) associated with that post, checks if any terms are found then adds each term as a class.
Please replace 'custom_type' and 'special_taxonomy' with your actual custom post type and custom taxonomy.