Site logo

Archived topic

ACF add class to body tag

6 replies · Started by Angie on August 28, 2022

Viewing posts 1–7 of 7

Hello!
I want to give my client an easy possibility to change the background image of the body of each page. My approach is to add a class to the body tag. I found this support topic and wanted to adapt it for my purpose, maybe you could help?
https://generatepress.com/forums/topic/body-class-for-categories-and-acf-field/

So I added a costum field to the pages with a dropdown menu, where the client can choose a class-name, that should be added to the body tag. With costum CSS I set the corresponding background image.

The field name is: bild-header

CSS:

body.eichhorn {
	background-image:url("http://b3q5oy.myraidbox.de/wp-content/uploads/2022/07/images_HOME-squirrel_screen600.jpg");
	 background-position: right top; 
  background-repeat: no-repeat; 
  background-size: 40vw;
}

Now I took the code from the support topic and added it to functions.php: But how can I adapt it, so it just adds the fields content as class to the body tag? I guess I don't need the elseif that refers to categories?



add_filter('body_class','add_category_to_single');

function add_category_to_single($classes) {

    global $post;
    $value = get_field('bild-header'); // The ACF Field
    
if ( is_page() ) {
        $classes[] = $value; // Supposed to take the ACF Field Value
    }   
 
elseif (is_singular() ) {
        
        foreach((get_the_category($post->ID)) as $category) {
            $classes[] = $category->category_nicename . $value;
        }
    
    }

    
    return $classes;
}

Thank you very much!
Angie.

Hi again! Does someone have an idea for this? Thank you very much! Angie.

Hi there,

sincere apologies for missing your original topic, lets take a look.

Try this:

add_filter( 'body_class', 'add_acf_body_class' );

function add_acf_body_class( $classes ) {

    global $post;
    )
    // Get the ACF Field 
    $value = get_field( 'bild-header' ); // The ACF Field

    // Check if $value exists
    if ( $value ) {
        // load $classes with ACF value
        $classes[] = $value; 
    }
    
    return $classes;
}

Thank you! and please don't apologise for your amazing support!!
Could it be, that there is a bracket missing?
Angie.

Hi Angie,

Can you try this instead?:

add_filter( 'body_class', 'add_acf_body_class' );

function add_acf_body_class( $classes ) {

    global $post;
    
    // Get the ACF Field 
    $value = get_field( 'bild-header' ); // The ACF Field

    // Check if $value exists
    if ( $value ) {
        // load $classes with ACF value
        $classes[] = $value; 
    }
    
    return $classes;
}

Yes! This made it work. Thank you so much again!!
Angie.

You're welcome Angie!

This archived topic is closed to new replies.