[resolved] Undefined variable in function. (6 posts)

  1. I"m getting this error when I set WP_Debug to true -

    Notice: Undefined variable: parent in .../frank-timis/functions.php on line 134

    The function that I'm using is:

    function is_grand_child( $page_id_or_slug ) {
    	global $post;
    	if ( !is_int( $page_id_or_slug ) ) {
    		$page = get_page_by_path( $page_id_or_slug );
    		$page_id_or_slug = $page->ID;
    	if ( $post->post_parent ) {
    		$parent = get_post( $post->post_parent );
    	return ( is_page() && is_object( $parent ) && $page_id_or_slug == $parent->post_parent );

    And parent is defined right here: $parent = get_post( $post->post_parent );

    I don't see anything wrong with this and not sure if I should just ignore the error. The code works just fine otherwise.

    Any PHP coder have any idea?

  2. vtxyzzy
    Posted 3 years ago #

    $parent will not be defined if $post->post_parent is zero. I think you need to change the return statement to this:

    return ( $parent && is_page() && is_object( $parent ) && $page_id_or_slug == $parent->post_parent );
  3. Bah, still undefined. :(
    This is so strange.

  4. Joey Kudish
    Posted 3 years ago #

    @vtxyzzy was correct $parent will not be defined if $post->post_parent is zero, however his solution doesn't fix the issue since he's checking if $parent is true, still without checking if it's defined or not.

    Changing the return to the following will fix the issue since empty will return true if $parent is not defined

    return ( is_page() && ! empty( $parent ) && is_object( $parent ) && $page_id_or_slug == $parent->post_parent );

  5. Sweet! The error is now gone.
    Thanks a million!

  6. vtxyzzy
    Posted 3 years ago #

    OK, enlighten me. How can an undefined variable be evaluated to 'true'?

Topic Closed

This topic has been closed to new replies.

About this Topic


No tags yet.