0

I have 3 categories: Travel, Destination and Tips. I've been trying to get the latest post from each categories then put them into an array. Here's what I have in mind.

//GET CATEGORIES
//I have this code but this only selects one category
$args = array ( 'post_per_page' => 1, 'cat' => 16 ); 

//SELECT THE LATEST POST FROM EVERY CATEGORY
//This part I don't know what to do.

//GET ID OF THE POST SO THAT I CAN ADD IT TO THE ARRAY
$post   = array(); <-- This should contain every latest post from the categories.
$post[] = get_post( /*ID OF THE POST SHOULD BE HERE*/ );

What I want to achieve is to have the id's of the latest posts from every category in the array. Please help. Thank you.

2
  • You will have to run 3 different queries and collect post ids from each.
    – Robert hue
    Oct 9, 2014 at 7:01
  • @Roberthue that's been the thing that's in my mind however isn't it possible like doing a foreach loop? I've seen it but not sure if it works in my case. Oct 9, 2014 at 7:06

1 Answer 1

1

Ok you can use a foreach loop to return the latest post from each category. Here is how you should do that.

<?php

    $postids = array();
    $catids = array( 1, 2, 3 ); // add category ids here.

    foreach ( $catids as $catid ) {

        $my_query = new WP_Query( array( 'cat' => $catid, 'ignore_sticky_posts' => 1, 'posts_per_page' => 1, 'no_found_rows' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false ) );

        if ( $my_query->have_posts() ) :

            while ( $my_query->have_posts() ) : $my_query->the_post();
                $postids[] = $post->ID;
            endwhile;

        endif;

        wp_reset_postdata();

    }

    print_r( $postids ); // printing the array.

?>

It's practically the same as running the 3 different loops but code is much cleaner now.

6
  • Let me check that ;) Oct 9, 2014 at 7:17
  • cool but what's wth the wp_reset_postdata and cache thing? Oct 9, 2014 at 7:21
  • wp_reset_postdata() is to reset the query after getting IDs in each category. And I added update_post_term_cache and update_post_meta_cache because we do not want WordPress to also fetch post metadata and other details so WP_Query will be faster. Although you can remove these if you find it confusing.
    – Robert hue
    Oct 9, 2014 at 7:23
  • MY GOODNESS! MY PROBLEM FOR MONTHS IS NOW SOLVED! THANKS A LOT ROBERT! :))))))))))))) Oct 9, 2014 at 7:27
  • Thank you for the cache thing as well. It's very useful! Oct 9, 2014 at 7:28

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.