Working on my pet project, I came across a conditional that was very conspicuously missing from the Wordpress core template functions. Where has my is_child() been misplaced?
Building web sites using Wordpress, you’ve probably more than once found yourself using various conditional tags to determine whether you’re on a page, a category, a blog entry, or something else. You can specify exactly what page you’re looking for with is_page(), whether you’re on the front page with is_home(), or whether you’re visiting an archive page with is_archive(). But what if you’d like to know who your parent was, or if you even had one?
I know who my parents are, they were introduced to me by the doctor, and over the years we eventually got to a point where we could remember each others names. It’s a little trickier to know who your parent is in Wordpress, though altogether not very difficult. You can check your $post object to see if you have a parent, and run get_post() if you’d like to know your parents name.
But what if you need to check this often?
Instead of writing the same few checks over and over again on various pages or in different functions, it would be nice if Wordpress had an is_child() function as part of the core. So I wrote one, and I believe in laziness, and everyone else’s right to that same laziness.
My code highlighter has gone on vacation, and I haven’t got the time right now to call in a substitute… sorry! Seems to be working again.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function is_child ($of_page = NULL) { global $post; if (! $post->post_parent || ! is_page()) return FALSE; if (! isset($of_page)) return TRUE; else if ($of_page == $post->post_parent) return TRUE; else if ($of_page == get_post($post->post_parent)->post_name) return TRUE; return FALSE; } |
Add this as a plugin, or in your functions.php, and you can use it in the same way you would use is_page();
1 2 3 | if ( is_child() ) // returns true if the page is a child of any if ( is_child(12) ) // returns true if the parent ID is 12 if ( is_child('about') ) // returns true if the page slug of the parent is 'about' |
Enjoy!