I'm not quite sure how your grandparent pages are getting the style since your code says to grab the field from the parent. The grandparents' post parents should be 0, meaning they don't have parents. Perhaps there's something I'm missing about your hierarchy.
A conditional should work here:
(assumes you've already specified global $post
in your template):
<div class="<?php
// if this is a top-level post, grab its field
if($post->post_parent == 0) { ?>
// output the field - no need to pass an ID as it is the ID of this post
the_field('colour');
// if this is not a top-level post (child, grandchild, or so forth)
} else {
// get all of this post's ancestors: parent, grandparent, and so forth
$ancestors = get_post_ancestors();
// get the last item in the array - the "top" parent (grandparent)
$id = end($ancestors);
// now pull its field
the_field('colour', $id);
} ?>
">
A non-ACF way to achieve the same effect would be to add your desired classes to the <body>
class in functions.php
:
<?php // add a filter to the body_class() function
add_filter('body_class', 'wpse_310439');
function wpse_310429($classes) {
// pull ancestors of the current page/post/cpt
$ancestors = get_post_ancestors();
// if this is a particular page ID, or a child of that ID
if(is_page('12345') || end($ancestors) == '12345') {
// add a class to the <body>
$classes[] = 'blue';
} elseif(is_page('54321') || end($ancestors == '54321') {
$classes[] = 'yellow';
}
// always return $classes so body gets regular classes
return $classes;
} ?>
With this way you're setting the classes in theme files, and you'll also need to use the cascade to target whichever div needs the coloring (instead of .blue
you would use something like body.blue div.styleme
), but no plugin is needed. :)