Undefined property: WP_Query::$post

I am working on some rather elaborate comparisons between metadata and having a bit of trouble correctly referring to results from my query. The first query to establish $team_is_home works fine but as soon as I try to capture the ID of the posts where the $team_is_homeit goes a bit haywire and I get warnings saying: “Undefined property: WP_Query::$post ”

$args = array(
       'post_type' => 'match_report',
       'post_status' => 'publish',
       'meta_query' => array(
           array(
                 'key' => 'report_home-select',
                 'value' => $team_id,
                 'compare' => '=',
           ),
       )                                  
     );

    $hometeams = new WP_Query($args);       
    $team_is_home =  $hometeams->found_posts;
    $scorehome = get_post_meta($hometeams->post->ID, 'report_homescore'); 

How should I be reffering to $hometeams->post->ID to avoid getting this warning?

Related posts

3 comments

  1. First of all post field of WP_Query is current post ID and not post object. But I don’t think you should use it before calling the_post() method.

    Normally you should do it in this way:

    $args = ...
    $hometeams = new WP_Query( $args );
    $teamishome = $hometeams->have_posts();
    while ( $hometeams->have_posts() ) {
      $hometeams->the_post();
      $scorehome = get_post_meta($post->ID, 'report_homescore', true); // you want only one meta, not all array I guess.
      ...
    }
    
  2. If you var_dump($hometeams); you will see that $hometeams->post is set to the first post in the query results even before $hometeams->the_post runs. WP_Query initializes it automatically if you have posts in the result set.

    The “Undefined Property” warning occurs when your result set is empty, and thus $hometeams->post can’t be set/initialized.

    You need to check that you have a populated $hometeams->post before trying to use it. If you use while ( $hometeams->have_posts() ) { as suggested in one answer or foreach($hometeams->posts as $key => $post){ as in another you are looping over $hometeams->posts and so are avoiding the issue with $hometeams->post completely.

    Another option would be…

    if (!empty($hometeams->post)) {
      $scorehome = get_post_meta($hometeams->post->ID, 'report_homescore'); 
    }
    

    … however, since your query does not contain 'posts_per_page' => 1 you need to be using a loop or you will only get one of the potentially large number of posts in the result set.

    Be sure to run reset_postdata after your secondary Loop to reset $post, or wp_reset_query if necessary.

  3. You can do it with foreach also

    $args = ...
    $hometeams = new WP_Query( $args );
    foreach($hometeams->posts as $key => $post){
        echo get_post_meta($post->ID, 'report_homescore', true);
    }
    

Comments are closed.