0

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;
}

1 Answer 1

1

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
11
  • After adding the above to my functions.php file, how do I add the value to the post Emertop? Will the body class be the inputted value for $btag?
    – AndrewL64
    Aug 5, 2015 at 19:43
  • I'm not sure what you mean exactly. The value loaded to the $btag variable will be inputed to the class of body tag. It's a filter, it's the way how you can change various values across WP.
    – Emetrop
    Aug 5, 2015 at 19:52
  • So whatever value I assigned to the btag field will be added as the post body class right?
    – AndrewL64
    Aug 5, 2015 at 19:53
  • Exactly. But there is one condition, your theme have to call body_class function in body tag. But each good theme do this so it should work everytime. You can check header.php file in your theme if it's there. If not, just add it to the body tag like this <body <?php body_class(); ?>>
    – Emetrop
    Aug 5, 2015 at 19:57
  • I build the theme from scratch myself Emertrop. This is the body tag right now: <body <?php body_class( $class ); ?>>
    – AndrewL64
    Aug 5, 2015 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.