Support » Fixing WordPress » Undefined variable in function.

  • Resolved Christine Rondeau

    (@crondeau)


    Volunteer Forum Moderator

    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?

Viewing 5 replies - 1 through 5 (of 5 total)
  • $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 );
    Christine Rondeau

    (@crondeau)

    Volunteer Forum Moderator

    Bah, still undefined. 🙁
    This is so strange.

    @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 );

    Christine Rondeau

    (@crondeau)

    Volunteer Forum Moderator

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

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

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Undefined variable in function.’ is closed to new replies.