0

I have 2 custom post types:

  1. Drama
  2. Episode

Drama is Parent, and Episode is child. Now, for instance I add 2 dramas and and then add episodes (Drama 1, Drama 2 as Parent):

Drama 1

  1. --- Episode 1
  2. --- Episode 2 ** updated
  3. --- Episode 3
  4. --- Episode 4 ** updated

Drama 2

  1. --- Episode 1
  2. --- Episode 2
  3. --- Episode 3
  4. --- Episode 4
  5. --- Episode 5
  6. --- Episode 6
  7. --- Episode 7 ** updated
  8. --- Episode 8 ** updated

** updated shows the episode was recently updated.

On Homepage, I want to display all posts from "Episode" post type order by post_modified. So with above example it shows the following on homepage:

Sorted by post_modified..

  1. Episode 8 - Drama 2
  2. Episode 7 - Drama 2
  3. Episode 2 - Drama 1
  4. Episode 4 - Drama 1
  5. Episode 1 - Drama 1
  6. Episode 3 - Drama 1
  7. Episode 1 - Drama 2 .. .. ...

It displays all 12 episodes ordered by post_modified.

THE PROBLEM..

Since I have only 2 Dramas, I want to display only 2 most recently updated episodes from those dramas (only 1 post from every parent), I dont want to show all episodes. So the desired output on homepage should be only following 2 episodes:

  • Episode 8 - Drama 2
  • Episode 4 - Drama 1

I used WP_Query to display episodes, however it displays all posts. How can I limit episodes and get only 1 most recently updated episode from each Drama.

 $wp_query = new WP_Query( array(
    'post_type' => 'episode',
    'orderby' => 'post_modified',
    'order'   => 'DESC',
    'suppress_filters' => true,
    'posts_per_page' => 100,
    'paged' => $paged
    
 ));

Edit - Update: Rephrased and removed another similar question.

Edit 2: The number of Dramas and Episodes are just for example, the actual number of Dramas is over 20K and Episodes over 300K.

1 Answer 1

0

I think maybe you don't need Wp_Query. I believe you can just do

$episodes_for_front_page = array();

//get the two dramas
$dramas = get_posts(array('post_type' => 'drama'));

foreach ($dramas as $drama){
  
  //get all the episodes belonging to that drama, sorted by most recent update
  $episodes = get_posts(
    array(
      'post_type' => 'episode',
      'post_parent' => $drama->ID,
      'orderby' => 'post_modified',
      'order' => 'DESC'
    )
  );

  //add the most recent episode to the list of posts to display
  $episodes_for_front_page[] = $episodes[0];
}
1
  • Thanks but this may bot work, as I posted number of episodes and dramas as an example, the actual posts under Dramas are more than 20K and under Episodes over 300K, secondly with this I cannot get the most recently updated Episode, it will just query Dramas first but infact Episodes are the ones which are updated/added.
    – Themer
    Jul 6, 2021 at 16:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.