X

Check If a Page is a Child (Advanced w/ ID or SLUG)

Need to find out if a particular page on your WordPress website is a Child or not? This code will allow you to do just that.

Using this function returns true of false if the page the user is on equals the $pid or is a child/ancestor of the page.
The is_child() function can be used by passing the ID or the SLUG.

Both is_child(14) and is_child(“about-us”) are accepted.

There are many ways to use this function so be creative!

Code Snippet:

<?php

/*
* 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">


*/


?>

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!