Thanks alchymyth. I have been fiddling around with WP_Query for ages but can’t work out how to combine it with what I’ve done so far – for some reason it’s not working.
This is all going in a copy of page.php which I’m using as my static front page, if that’s any help.
get_posts() uses WP_Query allowing it to use the same parameters.
http://codex.wordpress.org/Template_Tags/get_posts#Parameters
For example, to narrow your current query to posts with tags that have the slugs “tag1” and “tag2”:
$args = array(
'numberposts' => 5,
'order' => 'DESC',
'orderby' => 'post_date',
'tag_slug__in' => array( 'tag1', 'tag2' )
);
Just to summarise:
I can list the latest 5 posts using the code in my original forum post above.
Separately, I can list ALL posts tagged with a certain keyword (hotpost) using this…
<?php
$the_query = new WP_Query( 'tag=hotpost' );
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<?php the_time('F j, Y'); ?>
<a href="<?php echo get_permalink(); ?>">
<?php the_title(); ?>
</a>
<?php the_excerpt(); ?>
<?php endwhile;
wp_reset_postdata();
?>
What I can’t work out is how to combine these two snippets.
- The first code snippet, which uses a foreach loop, lists the five most recent posts but doesn’t filter by tag.
- The second code snippet (above), which uses a while loop, filters by tag but doesn’t restrict the number of posts to five.
(As you can probably tell I’m no natural coder, so apologies if the solution to this is obvious!)
(Sorry Big Bagel, only just noticed your post. Will look at it now.)
If you’d prefer to use WP_Query instead:
$args = array(
'posts_per_page' => 5,
'tag' => 'hotspot'
);
$the_query = new WP_Query( $args );
Done it!! Thanks all. I didn’t know you could have an array in an array like that. I just needed to add that tag_slug__in property that you mentioned Big Bagel.
Full working code:
<?php
$args = array( 'numberposts' => 5, 'order'=> 'DESC', 'orderby' => 'post_date', 'tag_slug__in' => array( 'hotposts' ) );
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
<?php the_time('F j, Y'); ?>
<a href="<?php echo get_permalink(); ?>">
<?php the_title(); ?>
</a>
<?php the_excerpt(); ?>
<?php endforeach;
?>