Retrieve latest post by multiple categories with ID

The problem is that if you pass multiple category to a query, then you’ll retrieve 4 posts ordered by date, but if you last 4 posts are all in one category, you’ll get all 4 posts from same category.

You have 2 choices: run 4 different queries, one per category, and retrieve one post per query or run a custom sql query that retrieve the posts taking care of getting one post per category.

I’ll give you a solution for the second choice.

The code is most taken form here.

function get_unique_post_by_tax( $tax = 'product_cat_', $ids="", $cpt="product") {
  global $wpdb;
  $ids = array_filter( array_map( 'intval', (array) $ids ) );
  if ( empty($ids) ) return false;
  $ids_txt = implode( ',', $ids );
  return $wpdb->get_results( $wpdb->prepare(
    "SELECT p.* FROM $wpdb->term_relationships
    JOIN $wpdb->term_taxonomy AS tt 
    ON tt.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
    JOIN $wpdb->posts AS p ON p.ID = $wpdb->term_relationships.object_id
    WHERE tt.taxonomy = %s 
    AND tt.term_id = IN (%s)
    AND p.post_type = %s AND p.post_status="publish"
    GROUP BY $wpdb->term_relationships.term_taxonomy_id
    ORDER BY post_date DESC LIMIT %d",
    $tax, $cpt, $ids_txt, count($ids)
  ) );
}

Put previous function in functions.php after that, you can use it like so:

$loop = get_unique_post_by_tax( 'product_cat_', array(82,83,84,85) );

if ( ! empty($loop) ) {
  global $post;
  foreach ( $loop as $post ) :
    setup_postdata($post);
  ?>
    <h2><a href="https://wordpress.stackexchange.com/questions/127509/<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>;
  <?php
  endforeach;
  wp_reset_postdata();
}