Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Help with statement WordPress

  • SOLVED

Hi, I am using this code to style the page title depending on the parent, but sometimes I have pages that are a few levels deep, I want to check the pages grandparent also.

So for example the below code works fine for Page A, but not for Page B which is a child of Page A.

Parent Page
- Page A
- - Page B

<?php wp_reset_query();
global $post;
if ( $post->post_parent == 8 ) { ?>
<div class="pagetitleshops"><?php the_title(); ?></div>
<?php } else if ( $post->post_parent == 35 ) { ?>
<div class="pagetitlefood"><?php the_title(); ?></div>
<?php } else if ( $post->post_parent == 36 ) { ?>
<div class="pagetitlemusic"><?php the_title(); ?></div>
<?php } else { ?>
<div class="pagetitle"><?php the_title(); ?></div>
<?php } ?>


I found this bit of code, is this what I need and how would I include it into my code?

$ancestors = get_post_ancestors($post);
if (in_array(77,$ancestors)) echo "77 is an ancestor of the post";


Found here: http://wordpress.org/support/topic/depth-of-post-gtpost_parent

Thanks

Answers (2)

2013-04-04

Sébastien | French WordpressDesigner answers:


<?php

wp_reset_query();
global $post;

if ($post->post_parent) {
$parent = $post->post_parent;
$ancestors = get_post_ancestors($post->ID);
}
if (( $parent == 8 ) OR (in_array(8,$ancestors))) { ?>
<div class="pagetitleshops"><?php the_title(); ?></div>
<?php } else if (( $parent == 35 ) OR (in_array(35,$ancestors))) { ?>
<div class="pagetitlefood"><?php the_title(); ?></div>
<?php } else if (( $parent == 36 ) OR (in_array(36,$ancestors))) { ?>
<div class="pagetitlemusic"><?php the_title(); ?></div>
<?php } else { ?>
<div class="pagetitle"><?php the_title(); ?></div>
<?php } ?>

2013-04-04

Arnav Joy answers:

try this


<?php wp_reset_query();

global $post;

if ($post->post_parent) {
$ancestors=get_post_ancestors($post->ID);
$root=count($ancestors)-1;
$parent = $ancestors[$root];
} else {
$parent = $post->ID;
}

if ( $parent == 8 ) { ?>

<div class="pagetitleshops"><?php the_title(); ?></div>

<?php } else if ( $parent == 35 ) { ?>

<div class="pagetitlefood"><?php the_title(); ?></div>

<?php } else if ( $parent == 36 ) { ?>

<div class="pagetitlemusic"><?php the_title(); ?></div>

<?php } else { ?>

<div class="pagetitle"><?php the_title(); ?></div>

<?php } ?>