I have 3 different custom post types: 1.) "events"
, 2.) "winners"
and 3.) "offers"
. How would I go about retrieving the first (latest) post in each of these post types on a single web page (i.e a home page).
Would I use get_posts()
or would I have to manipulate the_loop()
?
Yes, get_posts is the safest way to use multiple loops. It does not mess up with the original query.
Another way would be to create new WP_Query objects:
Note: Why you should not use query_posts()
Hi @dotty:
The answer from @sorich87 is correct, but I thought I’d elaborate a bit. I’ve coded a class for you called (verbosely)
LatestPostPerPostTypeQuery
and you can use it in the loop in place ofWP_Query
, like so:Below is the code for the
LatestPostPerPostTypeQuery
class which you can copy into your theme’sfunctions.php
file (or use the code in a plugin if you like.) The nice thing about this alternative toWP_Query
is it does a single query to the database instead of one for each of the three post types like you’d be forced to use when usingWP_Query()
directly.I’ve also posted a standalone file on Gist allowing you grab the source code and drop the example into a file in the root of your website to call it directly from the browser to watch it in action: