wordpress-function
is_child() not working – Fixed

Like me many of you may have been using the is_child() in your functions.php file of your template for a while now as it not only detects immediate children, but also if the page being tested exists anywhere in the page hierarchy.

However as I upgrade my sites to WordPress 3.1 the code below suddenly stop working or works sporadically.

<?php
	 function is_child($pid) {      // $pid = The ID of the page we're looking for pages underneath
        global $post;         // load details about this page
        $anc = get_post_ancestors( $post->ID );
        foreach($anc as $ancestor) {
            if(is_page() && $ancestor == $pid) {
                return true;
            }
        }
        if(is_page()&&(is_page($pid))) 
                   return true;   // we're at the page or at a sub page
        else 
                   return false;  // we're elsewhere
    };
?>

So, ..after a little looking, testing, searching and head scratching I have a solution, which shows that there has been clearly a phasing out or adjustment in the way the get_post_ancestors() functions returns the parent pages, ..however, in the interests of quick fixes and not boring you with the hows, whys and whats, ..here is the new working function.

<?php
    function is_child($post_id) {
		global $wp_query;
		$ancestors = $wp_query->post->ancestors;
		if(isset($ancestors)){
			if (in_array($post_id, $ancestors) ) {
				$return = true;
			} else {
				$return = false;
			} 
		} else {
			$return = false;
		}
		return $return;
	}
?>

Now get back to work, .as I must

Leave a comment...

This site is not up to date. I really should take it down and make a new one as I have been busy with a lot of cool projects and clients recently, but currently do not have the time to rebuild it.

So, it stays here, but please note it has not been updated in a while and if you need to get in contact with me please just email me directly at mog@mogmachine.com or phone me on +44 (0)7960 214407.

Thanks,

Marcus (mog)