WordPress Code Snippets — Detecting Page Parent, Child And Ancestor

Wordpress offers conditional tags for checking various conditions to output the required content for specific templates. Likewise, is_page(), is_home(), is_single(), etc come in handy for displaying conditional content and yes, to create custom templates for home page, front page or any other page.

But there are some petty conditions for which the conditional tags are missing. For example, there are no specific conditional tags to check the parent of the page, child of the page and ancestor of the page.

Here are quick code snippets to add to your functions.php or custom_functions.php which will allow you to simply check whether a page is a parent or child or an ancestor.

Is Page A Parent Of Any Page [To Check If A Page Has Subpages]

function is_parent()
{
    global $post;
    $pages = get_pages("child_of=".$post->ID);
    if ($pages) return true;
}

Usage:

if (is_parent()){
//custom code
}

Is Page A Child Of Specific Page

function is_child($post_id)
{
    global $post;
    if(is_page()&&($post->post_parent==$post_id)) 
               return true;  
    else 
               return false; 
}

Usage:

if (is_child(5)){
//custom code
}

Is Page An Ancestor Of Specific Page

function is_ancestor($post_id) {
    global $wp_query;
    $ancestors = $wp_query->post->ancestors;
    if ( in_array($post_id, $ancestors)) {
        return true;
    } else {
        return false;
    }
}

Usage:

if (is_ancestor(5)){
//custom code
}

Quick Tip: You can define these functions in functions.php and use these conditions for creating custom templates or use them with widget logic (the WordPress plugin that allows you to display widgets conditionally).

Stay Updated!

Join 37,807 others and get tips on design & development using Wordpress on Genesis, Lander and WooCommerce!

Need help with Wordpress or business websites?

Hi, I’m Shivanand Sharma. I’m a WordPress Genesis designer and have developed several WordPress plugins and themes. Here are some of my latest contributions:

I’m also a WordPress Consultant and specialize in making WordPress work for your business.

Get in touch and let's get the ball rolling!Contact Me

To post a comment…

Comment on WordPress Code Snippets — Detecting Page Parent, Child And Ancestor