List ‘n’ number of posts from a Tag, each with a different class or ID

get_posts() is for ‘secondary’ loops – ones that exist along-side the main Loop, usually in a side-bar or at the bottom listing ‘related’ posts etc. get_posts() is called from within a template page. So it is the wrong thing to use here.

You’ll want to alter the main query as outlined in: When to use WP_query(), query_posts() and pre_get_posts

add_action('pre_get_posts','wpse50857_alter_query');
function wpse50857_alter_query($query){

      //Check other conditionals depending on when you want to alter the loop
      if( $query->is_main_query() && is_home() ){

        $tax_query = array(array(
                        'taxonomy' => 'post_tag',
                        'field' => 'slug',
                        'terms' => 'my-tag'
                      ));
        $query->set('tax_query',$tax_query);
        $query->set('posts_per_page',5);
      }
}

Note this over-rides any previous tax_query (this doesn’t matter in this context – but if it should you can get the previous tax_query and merge it with the new one…)

Other conditionals available here.

To edit how the posts are display, you’ll need to edit the appropriate template page (home.php?, front-page.php?).

The loop will be something like:

if( have_posts() ):
    while( have_posts() ): the_post();
       //The loop 
      ?>
       <h1 class="entry-title"><a href="https://wordpress.stackexchange.com/questions/50857/<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
  <?php
    endwhile;
endif;

and you can edit that the display whatever you like.

Leave a Comment