New error notice for WP_Post::$ancestors in 3.5

Problem: This problem is with the newest version of WordPress. User has used this function without problems in the past, but in 3.5. He has received an error notice, which reads:
Notice: Indirect modification of overloaded property WP_Post::$ancestors has no effect in /mysite.com/public_html/wp-content/themes/mytheme/functions.php on line 09
Line 9 is:

return end($post->ancestors);
function get_top_parent_page_id() {

global $post;

// Check if page is a child page (any level)
if ($post->ancestors) {

// Grab the ID of top-level page from the tree
return end($post->ancestors);

} else {

// Page is the top level, so use it’s own id
return $post->ID;

}

}

The function he has found at:
http://www.webcitizenmag.com/2010/05/20/how-to-get-top-parent-page-id-in-wordpress/
Is this any bug in wordpress Or is there something that changed in the core code?
The function still works properly if he does not has set debug to true.

Solution 1:
Try replacing this code:
return end($post->ancestors);
With this:
return end( get_post_ancestors($post) );

Solution 2:
I think that this is due to the ancestors property is no-longer loaded by default.The thing is that when you call the ancestors property, PHP checks that it’s not a property that has been created for that WP_Post object. So PHP tries to call the __get() method of the class in the case of WP_Post exists. This is a magical method in PHP used to auto load properties for an object.
Can you try with this code:

function get_top_parent_page_id() {

global $post;

$ancestors = $post->ancestors;

// Check if page is a child page (any level)
if ($ancestors) {

// Grab the ID of top-level page from the tree
return end($ancestors);

} else {

// Page is the top level, so use it’s own id
return $post->ID;

}

}

Conclusion:
Both of the above solutions can solve that problem. You can use any one of them. So enjoy.

Leave a Reply

Your email address will not be published. Required fields are marked *