When I need to get a single post type list I usually use get_posts, how can I retrieve multiple custom posts types to populate the site homepage?

To be more precise, I would like to get the latest mixed posts (so mixed slugs like work, photo, code) and oreder them by date.

I could call get_posts per each custom post type and then filter them, but I was just wondering if there was a more optimized way to do it, something like:

<?php
$args = array (
    'post_type' => array ('work', 'photo', 'code', 'post'),
    'numberposts' => 5,
    'orderby' => 'post_date',
    'order' => 'DESC'
);
$posts_array = get_posts($args);
?>

So, does exists some way to get a mixed post type list?

link|improve this question

67% accept rate
feedback

1 Answer

up vote 1 down vote accepted

The post_type argument of the get_posts() function is for retrieving different types of post content. I'm assuming here that 'work', 'photo', and 'code' are custom post types.

Grabbing multiple post types with WP_Query

Instead of using get_posts(), you can use the WP_Query class to grab multiple post types. I just tested the following on my local install:

<?php

$q = new WP_Query(array(
    'post_type' => array('event', 'post')
));

while ($q->have_posts()) : $q->the_post();

?>

// ... the loop goes here as usual
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>

<?php endwhile; ?>

This grabbed posts of type "event" and of type "post" for me and displayed them by date. You can learn a lot more about the WP_Query object on the codex page. There's even a section specific to querying types and parameters.

Note that you do need to reference the object returned when instantiating the WP_Query object at the top of the loop with something like $q->, but you don't need to do this inside of the loop.

link|improve this answer
perfect! this is exactly what I was looking for. – vittorio Feb 16 at 9:16
feedback

Your Answer

 
or
required, but never shown

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