Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Hopefully it will be an easy question.

I created Wordpress template and now i would like to use that template for for several pages, however i would like to have different background color on some of the elements such as footer, header etc. that will be depending on parent. So lets say i have PARENT A (green background) and PARENT B (white background) now when i will create child of PARENT A i would like it to have green background automatically I know something similar could be done with posts using

<div class="post <?php foreach((get_the_category()) as $cat) { echo $cat->cat_name . ' '; } ?>"> </div>

I need some advice what would be the best way to do that.

I hope it makes sense, sorry if i made it confusing.

Many thanks,

share|improve this question
1  
possible duplicate of changing background color depending on parent page –  Chris_O Apr 30 '11 at 12:59

3 Answers 3

Using body_class(), by default, WordPress adds classes like parent-pageid-43 to it. This only goes one level deep, though.

The code below works for any ancestors of your parent pages, not just children. It relies on the is_page_or_ancestor plugin for that.

As kaiser said, body classes are the way to go. You can define the name of the classes for each template yourself by modifying the $parents array.

add_filter('body_class', 'my_body_class', 10, 2);

function my_body_class($wp_classes, $extra_classes)
{
    // List of parent pages with custom template
    $parents = array(
        // page ID => body class
        43 => 'template-a',
        57 => 'template-b',
    );

    // Loop over each parent
    foreach ($parents as $page_id => $class)
    {
        // http://wordpress.org/extend/plugins/is-page-or-ancestor/
        if (is_page_or_ancestor($page_id))
        {
            // Add body class
            $wp_classes[] = $class;
        }
    }

    // Add the extra classes back untouched
    return array_merge($wp_classes, (array) $extra_classes);
}
share|improve this answer

You might want to look at $post->post_parent having the global $post inside your loop, based on that you could pick your background color.

share|improve this answer

Easy via css if you use the <body <?php body_class(); ?>> function in your templates. This would give you a class of .page-child on child-pages that can be easily styled. Simply copy your styles and prefix the definitions with .page-child. Then re-style them.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.