Sometimes it’s useful to know whether the current post or page is within a specified hierarchical section of the site.
For example, I may have a page on my site called “Super Funky”, and some child pages dedicated to James Brown, Sly Stone, Parliament-Funkadelic, etc. On these pages, I have some special code that prevents them from uncontrollably getting down on the dancefloor… but the question is, how do we set up the logic that will check whether we are within the Super Funky section of the site?
Let’s say the Super Funky page’s ID number is 74. I could easily check to see if the current page has page-id-74 as an ancestor with the following code:
$ancestors = get_post_ancestors($post);
if(in_array(74, $ancestors)) {
// Code that will be parsed when this page has a ancestor with id 74
}
I found that code snippet on Coen Jacobs' blog.
However, that code won't include the Super Funky page itself. So if we want to have some conditional logic for code that should only execute in the Super Funky section of the site, we might want to write a function and put it in the /wp-content/themes/my_theme/functions.php file. Here is my suggestion:
/* ********************************
is_in_section($section_post_id, $post_obj)
purpose: to see if the current post/page is either the descendant of a specified post/page,
or if it is the specified post/page itself.
args:
$section_post_id : this is the post id number.
$post_obj : this is the object returned by $wp_query->get_queried_object();
example:
if( !is_in_section(74, $wp_query->get_queried_object()) ){
//this code does not execute within page-id-74, or any of its descendants
}
******************************** */
function is_in_section($section_post_id, $post_obj) {
$post_ancestors = get_post_ancestors($post_obj->ID);
if( $post_obj->ID == $section_post_id || (in_array($section_post_id, $post_ancestors)) ){
return true;
}
else{
return false;
}
}
I hope that's useful!