Site logo

Archived topic

Inserting custom class on archive page

5 replies · Started by Andy on August 1, 2021

Viewing posts 1–6 of 6

Hi,
I'm trying to insert a custom class into the post title markup on the blog archive page so that I can use an ACF field checkbox to specify a different post title color on a post by post basis.

I'm using the following code to apply this to the body on individual posts and it works well:

function add_acf_body_class($class) {
	$value = get_field('title_color');
	$class[] = $value;
	return $class;
}
add_filter('body_class', 'add_acf_body_class');

However, on an archive page I need to target each post on the same page, so adding to the body class won't work. Could I use the generate_do_element_classes() to achieve this and if so could you advise me on how to go about it?

Many thanks,

Thanks for this it works great.

I need add another custom class to the body but because already have a function adding the title colour I can't seem to get it to work, I've tried the following code:

function add_acf_body_class_size_post($class) {
	$value = get_field('title_size');
	$class[] = $value;
	return $class;
}
add_filter('body_class', 'add_acf_body_class_size_post');

And this is my existing custom class which DOES work:

function add_acf_body_class($class) {
	$value = get_field('title_color');
	$class[] = $value;
	return $class;
}
add_filter('body_class', 'add_acf_body_class');

Is there a way I can add an array maybe to add multiple classes?

You could do a single function like this:

function add_acf_body_classes($classes) {
    $title_color = get_field('title_color');
    $title_size = get_field('title_size');
    if ($title_color) {
        $classes[] = $title_color;
    }
    if ($title_size) {
        $classes[] = $title_size;
    }
    return $classes;
}
add_filter('body_class', 'add_acf_body_classes');

I added some IF conditions, as it makes sense to only output something if it exists. Not sure its necessary - and the alternative stripped right back code would be:

function add_acf_body_classes($classes) {
    $classes[] = get_field('title_color');
    $classes[] = get_field('title_size');

    return $classes;
}
add_filter('body_class', 'add_acf_body_classes');

The $classes instead of $class is arbitrary, its just gives the code a little more readability

Thank you, works great!!

Glad to hear that

This archived topic is closed to new replies.