The error says it all. You are trying to get property ID
of non-object. That means that the $post
var is not an object.
You can get current post ID within a WordPress loop using get_the_ID()
, but actually you don’t need it in this case (see explanation below).
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$current_post_type = get_post_type( get_the_ID() );
// Use $query->post if you want to get
// current post object in full
// ex: $query->post->ID
}
// Do not forget to reset post data after a custom wp_query loop
// to restore global $post to main wp_query data
wp_reset_postdata();
}
PD: Actually, $query->the_post()
sets global $post
to current post within the loop, and get_post_type()
checks global $post
if it doesn’t receive a different post data or ID, that is why your code works as expected despite the error.