php - Add a custom class to the body tag using custom fields

admin2025-06-05  2

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;
}
Share Improve this question edited Dec 11, 2018 at 11:55 AndrewL64 asked Aug 5, 2015 at 19:11 AndrewL64AndrewL64 2034 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749109111a316437.html

最新回复(0)