Apr
23
2011

is_child() Conditional Function for WordPress

by   |  Posted in Tutorials  |  6 comments

I wrote a little function a while back to Check if a Page is a Child of Another Page in WordPress called is_child(). It used the page ID to return a true or false value dependent on if the current page was a child of the parent page specified. I have recently made a little change so that the function could now accept either a page ID or slug.

Here it is again with the changes:

function is_child($page_id_or_slug) { 
	global $post; 
	if(!is_int($page_id_or_slug)) {
		$page = get_page_by_path($page_id_or_slug);
		$page_id_or_slug = $page->ID;
	} 
	if(is_page() && $post->post_parent == $page_id_or_slug ) {
       		return true;
	} else { 
       		return false; 
	}
}

The modification was inspired by Helpful Page Functions for WordPress.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , ,

Short URL: http://bit.ly/dOxWm7

Discussion 6 Comments

  1. Ozh on April 25, 2011 at 1:43 pm

    (weird: this post is tagged WordPress, yet it doesn’t appear in the WordPress tag archive page…)

    • c.bavota on April 26, 2011 at 12:40 pm

      I just checked and it is right at the top. Might have been a ghost in the machine. ;)

  2. Bing on June 28, 2011 at 8:29 am

    Hi Bavota!

    Thanks for your function, I found it useful.

    I’m wondering if something like this can be done for categories?

    “If is child of category”

    Thanks,
    Keep up the good work!

  3. app development on July 6, 2011 at 2:16 am

    Thanks Bavota for sharing this code.It helped me a lot and yes is_child function can be used for the category as well or any other module where there is a sub category.Wordpress always comes up with surprises more you explore more function you can find out.Bavota,Can a wordpress be used to make the site which is compatible for mobile viewing I mean which supports WAP?IF yes then please share some articles on how to create those site.Thanks a lot

  4. Aanya Shaw on July 8, 2011 at 10:55 am

    Perfect! I think you just pointed me to the exact page I was looking for … WordPress rocks and your functions make it better, Bavota!

    Aanya Shaw