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_home
it 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?
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 callingthe_post()
method.Normally you should do it in this way:
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 usewhile ( $hometeams->have_posts() ) {
as suggested in one answer orforeach($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…
… 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
, orwp_reset_query
if necessary.You can do it with
foreach
also