I've been trying without luck to get a custom taxonomy slug to appear as a class in the body tag of WordPress. Perhaps it has to do with the fact that I'm using a custom taxonomy rather than the build in one.
I'm registering a custom PAGE taxonomy in functions.php as follows and it works fine.
add_action( 'init', 'create_page_taxonomies' );
function create_page_taxonomies() {
register_taxonomy('page_section', 'page', array(
'hierarchical' => true,
'labels' => array(
'name' => _x( 'Page Section', 'taxonomy general name' ),
'singular_name' => _x( 'page-section', 'taxonomy singular name' ),
'search_items' => __( 'Search Sections' ),
'all_items' => __( 'All Sections' ),
'parent_item' => __( 'Parent Section' ),
'parent_item_colon' => __( 'Parent Section:' ),
'edit_item' => __( 'Edit Section' ),
'update_item' => __( 'Update Section' ),
'add_new_item' => __( 'Add New Section' ),
'new_item_name' => __( 'New Section Name' ),
'menu_name' => __( 'Sections' )
),
'public' => true,
'rewrite' => array(
'slug' => 'page-section',
'with_front' => false,
'hierarchical' => true
)
));
}
This creates a 'Sections' menu option under Pages. It works just like Post Categories. I then created a taxonomy Term labelled Trip Planner (slug: trip-planner) I then add the following to functions.php to try and get the taxonomy term slug name to appear as a class on the body tag.
add_filter( 'body_class', 'themeprefix_add_taxonomy_class' );
function themeprefix_add_taxonomy_class( $classes ){
if( is_singular() ) {
global $post;
$taxonomy_terms = get_the_terms($post->ID, 'page-section');
if ( $taxonomy_terms ) {
foreach ( $taxonomy_terms as $taxonomy_term ) {
$classes[] = 'section-' . $taxonomy_term[0]->slug;
}
}
}
return $classes;
}
This second snippet is 'sort of' working, when added and I view page source, I can see 'section-' appear as a class on the body tag but the term slug value which is supposed to follow the dash is not present. My body tag now looks like this.
<body class="page-template page-template-elementor_header_footer page page-id-451 wp-custom-logo section- elementor-default elementor-template-full-width elementor-kit-6 elementor-page elementor-page-451">
Mostly Elementor page builder classes but the 'section-' is present. I edited the second function to reference the 'page-section' slug defined in the register_taxonomy function.
Additional info if helpful.
- WordPress: 6.4.2
- Page Builder: Elementor
- Custom Page Taxonomy Slug: page-section
- Taxonomy Term Name Example: Trip Planner
- Taxonomy Term Slug Example: trip-planner
- Expected Body Class to be Added: section-trip-planner
I must be missing something?!?
UPDATE:
The PHP error generated (see comment below) when I corrected the page-section to page_section let me to the solution. $taxonomy_term[0] is not an array it is an Std Object, therefor I just removed '[0]' and now everything works fine.