WordPress Ancestors and Custom Fields

I’m doing my first serious wordpress project and I’m loving the page ancestor scheme. One of the cooler things you can do is define custom fields or featured images for the top level page, and have the children pull it in. All you need is a way to find out who’s the parent of the current page.

WordPress leaves us with the solitary get_post_ancestors() which returns an array filled with the ID’s of the page’s parents, all the way up to the root. Not so helpful in the middle of your template… and what if you’re AT a top page? get_post_ancestors() returns null!

I wrapped it in a helper function that grabs the last element in the array or returns the current post ID in case of null. An alternative is to recursively follow the $post->parent_post links, but this is way simpler!

function get_top_id($mypost){
  //pass in a post, get the id of the top ancestor
  //or the post's id if it's the top
  $ancestors = get_post_ancestors($mypost);
  if($ancestors != null){
    //pull off the last element of the array
  } else {

So, what do we do if we have the ID of the parent? We can perform lookups on special content that we stored there, for example a featured image (cryptically referred to as a ‘Post Thumbnail‘). We do this through the function get_the_post_thumbnail()

<?php echo get_the_post_thumbnail(get_top_id($post));?>

Now we’ve defined a single header on our top page and all the children have it too. This works for custom fields attached to the parent in the same way. I defined some fields called ‘quote’ and I can access them via get_post_custom_values() :

$quotes = get_post_custom_values('quote',get_top_id($post));
foreach ( $quotes as $value ) { 
<div class="blockquote">
<?php echo $value ?>
<?php } ?>

Now my sidebar has a bunch of quotes from the head of the section all the way down to each child page.

This entry was posted in Science, Work. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s