How to display content for specific child pages in WordPress

Let’s say you’re looking to display content on your WordPress pages but only for child pages of a specific section of your site. Here’s how to do it in just a couple of steps.

First, add the following code to your theme’s functions.php file:


function is_tree($pid) {
  global $post;
    if(is_page()&&($post->post_parent==$slug||is_page($slug)))
      return true; 
    else
      return false;
};

Next, open your page.php theme template and add the following where you want the content on your child pages to display:


<?php  global $post; 
  if (is_tree('PARENT PAGE')) {
    echo 'YOUR CONTENT HERE';
  }
?>

Change PARENT PAGE to the name of your parent page. For example, if your parent page is Resources, then enter ‘resources’. This ensures your content will display but only on subpages of yourdomain.com/resources/.

Replace YOUR CONTENT HERE with your content.

Push the changes in these files to your theme directory and try it out.

Post a comment

Fred looking at his camera phone with a dumb grin on his hairy face About

I'm an Ottawa-based web designer and front end developer who's been in the industry since HTML was written in all-caps with inline CSS. I like writing about the web as well as my other creative interests. Follow me on Twitter

Discussion

Requests for help are welcome but my schedule means I may be unable to respond right away.