Support » Themes and Templates » Style one section (and it's decendant pages) differently

  • Resolved dsided

    (@dsided)


    I need to style an area of a site differently with multiple sub-subpages.

    Rather than attaching a page template to the 20+ pages, is there a way to target a page (or slug) perhaps and all it’s descendants?

    In pseudo code it would be:

    if we're under website.com/special-section/
    add a div with a class of "special-section"

    body_class() gives me page specifics such as page-template-XYZ and there is some info about Conditional Tags in the codex: https://codex.wordpress.org/Conditional_Tags

    Note: There is no function to check if a page is a sub-page. We can get around the problem:

    if ( is_page() && $post->post_parent > 0 ) {
        echo "This is a child page";
    }

    I’m guessing that only works in a loop as I’ve added this to the header (page ID is 6904) and nothing show up:

    if ( is_page('6904') && $post->post_parent > 0 ) {
        echo "<h1>Test</h1>";
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter dsided

    (@dsided)

    Solved this via https://codex.wordpress.org/Function_Reference/get_post_ancestors

    In the header add this to create a targetable body class:

    </head>
    
    <?php
    /* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
    $class = '';
    /* is it a page */
    if( is_page() ) {
    	global $post;
            /* Get an array of Ancestors and Parents if they exist */
    	$parents = get_post_ancestors( $post->ID );
            /* Get the top Level page->ID count base 1, array base 0 so -1 */
    	$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
    	/* Get the parent and set the $class with the page slug (post_name) */
            $parent = get_post( $id );
    	$class = $parent->post_name;
    }
    ?>
    
    <body <?php body_class( $class ); ?>>

    Thread Starter dsided

    (@dsided)

    Resolved 🙂

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Style one section (and it's decendant pages) differently’ is closed to new replies.