The problem arises from the use of the_post()
, which overwrites the global $post
. Use get_posts
instead of WP_Query
and loop over the results with a foreach
:
$query = get_posts( $args );
if( $query ){
foreach( $query as $thepost ){
$post_id = $thepost->ID;
$post_title = get_the_title( $thepost );
}
}