• Resolved zartgesotten

    (@wearitwell)


    Hi there! I turned on debug mode to make sure everything was ok with my theme and plugins and I’m getting this:

    Notice: Undefined variable: post in /xxxx.php on line 62
    Notice: Trying to get property of non-object in /xxx.php on line 62

    And this is what it says in those lines…

    // get taxonomies terms links
    function custom_taxonomies_terms_links(){
      // THIS is Line 62
      $post = get_post( $post->ID );
    
      // get post type by post
      $post_type = $post->post_type;

    … and so on….;-)

    Funny thing is : the function does what it is supposed to do but gives out these errors. Right now it’s all in the functions.php but I want to move it to its own plugin. But first I want to get rid of these errors. Can anyone explain or help?
    Thank you very much!
    Anja

Viewing 2 replies - 1 through 2 (of 2 total)
  • What it’s saying is that the $post variable doesn’t eixst inside your function when you try to access it. PHP functions are basically “closed cases” that can’t see any variables from the outside system. so when you ask for $post->ID, the function doesn’t know what $post is so it gives those warnings.

    The reason that it’s working as expected, is that by default the get_post() function will use the current global $post value if nothing is passed to it, so you get back the current post.

    To fix this is very easy. Just set $post as global so you will be working with the current global $post object too:

    function custom_taxonomies_terms_links(){
        global $post;
    
        // get post type by post
        $post_type = $post->post_type;

    That’s all there is to it.

    Thread Starter zartgesotten

    (@wearitwell)

    Ah… thank you very much.
    I knew about global $post; but I tried adding it at the top of functions.php, thinking it would work for all functions.
    I didn’t think of putting it INSIDE my function!
    THANKS again, also for explaining so nicely!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Undefined Variable post’ is closed to new replies.