You need to move the bulk of your code into the loop proper. This part:
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$ids[]= $post->ID;
endwhile;
}
When the_post()
executes, it populates the $post
global upon which a number of template functions depend. The problem is that you are running your foreach
Loop but not resetting that global.
You could use setup_postdata()
inside that foreach
but I don’t see the point. It looks like you can do the whole thing in the first Loop.