0

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.

1 Answer 1

2

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;
1
  • Brilliant! Thanks Tareq, just what I was looking for.
    – Rothbert
    Commented Oct 27, 2011 at 6:52

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.