-3

I've created a recursive function to find out if current page is a child of page in a page tree.

My function:

function is_ancestor_of( $page_name = null, $post ) {

  if(is_null($page_name))
    return false;

  // does it have a parent?
  if (!isset( $post->post_parent ) OR $post->post_parent <= 0 )
    return false;

  //Get parent page
  $parent = wp_get_single_post($post->post_parent);

  if ( $parent->post_name == $page_name ){
    echo $parent->post_name.' - '.$page_name;
    return true;
  } else {
    is_ancestor_of( $page_name, $parent );
  }
}

This is the code I'm testing with:

$is_parent = is_ancestor_of( 'account', $post );

if(!$is_parent) {
  echo '<br/> No match';
}

And this is the result:

account - account
No match

This shows that it does find a parent page names 'account', but it is not returning any data. I've also tested returning a string, but that is not working either.

Can anyone see what I'm doing wrong?

Steven
  • 19,224
  • 47
  • 152
  • 257

2 Answers2

3

Your problem seems that you're calling your function recursively but not returning the result from your recursive call.

Your line

is_ancestor_of( $page_name, $parent );

should probably just be

return is_ancestor_of( $page_name, $parent );
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • That will not work. Because the first time you call it, it will run into `if ( $post->post_name == $page_name )`. And since it has recursed twice, it still does notreturn any sensible data. – Steven Jul 15 '12 at 17:28
  • Solved it. By removing `if ( $post->post_name == $page_name )` and adding `return true;` at the bottom of the function solved it :) Thanks for the tip :) – Steven Jul 15 '12 at 17:33
0

Try echoing $parent->post_name just before the following line, and you might get a better understanding of what is happening.

 if ( $parent->post_name == $page_name ){
Joyce Babu
  • 19,602
  • 13
  • 62
  • 97