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).