Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've been using this snippet to generate a list of recent posts from particular categories in a widget.

I'm currently restructuring the site using custom post types and taxonomies and want to generate a list of recent posts from 3 custom post types, taxonomies and categories don't have to be part of the query at this stage but would be nice to know how to include them.

Bit of a PHP novice, can't seem to find a solution to this.

<ul>
<?php
$recentPosts = new WP_Query();
$recentPosts->query('showposts=10&cat=-4,-30,-19,112,137,125,128');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

Ok, seem to have solved it with this

$recentPosts = new WP_Query();
$recentPosts->query(array('showposts' => 9, 'post_type' =>
array('mycustomposttype1', 
'mycustomposttype2','mycustomposttype3')));

but still not sure if this is the best method so any feedback appreciated.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

You can use custom variables ($recentPosts) like this:

$recentPosts = new WP_Query(array('showposts' => 9, 'post_type' => array('mycustomposttype1',  'mycustomposttype2','mycustomposttype3')));
while( $recentPosts->have_posts() ) : 
    $recentPosts->the_post();

    the_title();

endwhile;

But if you want to use the loop like normal loop, you need to use $wp_query as the variable. Also, everyone uses the parameters directly to the class as a constructor.

$wp_query = new WP_Query(array('showposts' => 9, 'post_type' => array('mycustomposttype1',  'mycustomposttype2','mycustomposttype3')));
while( have_posts() ) : 
    the_post();

    the_title();

endwhile;
share|improve this answer
    
Brilliant! Thanks Tareq, just what I was looking for. –  Rothbert Oct 27 '11 at 6:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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