There are certain posts where I want to manually append a custom body class using custom fields.
How do I go about it appending the class to the body tag when a certain custom field is added to a post?
I have tried the following but the custom fields name tagbody
is not shown in the dropdown:
add_filter( 'body_tag', 'body_tag_name' );
add_filter( 'get_the_body_tag_name', 'body_tag_name' );
function body_tag_name( $name ) {
global $post;
$btag = get_post_meta( $post->ID, 'tagbody', true );
if ( $btag )
$name = $btag;
return $name;
}
There are certain posts where I want to manually append a custom body class using custom fields.
How do I go about it appending the class to the body tag when a certain custom field is added to a post?
I have tried the following but the custom fields name tagbody
is not shown in the dropdown:
add_filter( 'body_tag', 'body_tag_name' );
add_filter( 'get_the_body_tag_name', 'body_tag_name' );
function body_tag_name( $name ) {
global $post;
$btag = get_post_meta( $post->ID, 'tagbody', true );
if ( $btag )
$name = $btag;
return $name;
}
You want to use body_class
filter.
function prefix_add_body_class( $classes ) {
global $post;
// good to check
if( ! is_single() || 'post' !== get_post_type() ) {
return $classes;
}
$btag = get_post_meta( $post->ID, 'tagbody', true );
if ( empty( $btag ) ) {
return $classes;
}
$classes[] = $btag;
return $classes;
}
add_filter( 'body_class', 'prefix_add_body_class' )
EDIT:
You wrote me in the comments that the theme is your own theme. So you don't need to do it via a filter. Just do it right in your theme.
Edit the header.php file like this.
// some code above
$classes = array();
if( is_single() && 'post' === get_post_type() ) {
$btag = get_post_meta( $post->ID, 'tagbody', true );
if( ! empty( $btag ) ) {
$classes[] = $btag;
}
}
?>
<body <?php body_class( $classes ); ?>>
<?php
// some code below