Question

This is a bit of a head scratcher, I'm not sure how to go about this or even if this would be the best method.

However this is my scenario:

I need to apply a specific colour to a wordpress page. I was planning to create a metabox where the user is allowed to select one of 5 colours. Now this is where it gets a bit tricky, I want this colour selection to apply to all child pages as well.

Is there a way to check if a parent page has a specific metabox option selected?

Was it helpful?

Solution

You can do this with some fairly standard logic:

  • check to see if the post_meta value is set
  • check if this is a child, get the parent id, check if a post_meta value is set

Here's some code to show how this could work (within the loop):

if ( get_post_meta($post->ID, 'colour', TRUE) ) {
    $colour = get_post_meta($post->ID, 'colour', TRUE);
} elseif ( $post->post_parent && get_post_meta($post->post_parent, 'colour', TRUE) ) {
    $colour = get_post_meta($post->post_parent, 'colour', TRUE);
} else {
    $colour = '#fff'; // could put a default value here
}
//do something with $colour variable

And when you're outside the loop you can use get_queried_object() to access the post object. IE:

$queried_object = get_queried_object();

if ( get_post_meta($queried_object->ID, 'colour', TRUE) ) {
    $colour = get_post_meta($queried_object->ID, 'colour', TRUE);
} elseif ( $queried_object->post_parent && get_post_meta($queried_object->post_parent, 'colour', TRUE) ) {
    $colour = get_post_meta($queried_object->post_parent, 'colour', TRUE);
} else {
    $colour = '#fff'; // could put a default value here
}
//do something with $colour variable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top