Are you looking for a way to find out if a page on your WordPress site is a child page or not? While there’s probably a plugin for this, we have created a quick code snippet that you can use to check if a page is a child page in WordPress.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
/* * Checks if the page is the parent or a child of the page matching the $pid param * $pid can be the page slug or the page ID # * * This function is best used to display menus when the parent/top level menu item needs * a rollover state or special treatment. * * @param $pid (string or int) * returns true if current page ID matches , else return false */ function is_child( $pid ) { // = The ID of the page we're looking for pages underneath global $post; // load details about this page // if $pid is an ID if (is_int($pid)) { if ( is_page($pid) ) return true; // get the page's children if the ID of a child matches the return true $anc = get_post_ancestors( $post->ID ); foreach ( $anc as $ancestor ) { if( is_page() && $ancestor == $pid ) { return true; } } } // if is a page slug elseif (is_string($pid)) { // Get page by 'SLUG' $page = get_page_by_path( $pid ); if ($post->ID == $page->ID) { return true; } $anc = get_post_ancestors( $post->ID ); foreach ( $anc as $ancestor ) { if( is_page() && == $page->ID ) { return true; } } } return false; // we arn't at the page, and the page is not an ancestor } /* Used in a template: <img src="home<?php if (is_child(0)){?>-ro<?php } ?>.jpg"> or <img src="home<?php if (is_child('home')){?>-ro<?php } ?>.jpg"> if true equals <img src="home-ro.jpg"> */
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 7 best WordPress poll plugins to grow onsite engagement and how to set up download tracking in WordPress with Google Analytics.
Hi, there’s a syntax error on #39