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

The question:

I want to list ‘n’ number of posts (ordered by latest first) — post’s title linked to the post’s permalink — from a tag on my WordPress blog. I also want to assign each link its own class or ID.

I checked this doc on WordPress Codex, which is very relevant to what I need, but makes little sense to me (and I’m therefore unable to modify it to my needs).

Hope I am clear enough, if not, I can try to clarify.

EDIT: Just so it’s clear, I want to be able to list the posts wherever I want. Any template.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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="<?php the_permalink(); ?>" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"><?php the_title(); ?></a></h1>
  <?php
    endwhile;
endif;

and you can edit that the display whatever you like.

Method 2

I don’t know PHP, so’ll try to explain after showing you the example PHP code that’s needed to do what’s asked in the question.

CODE:

<!-- Featured Posts -->
<div id="featured-posts">
<?php
    $count = 0;
    $some_featured_posts = new WP_Query(array('tag' => 'example2', 'posts_per_page' => 7));
    while ($some_featured_posts->have_posts()): 
        $some_featured_posts->the_post();
        $count++;
?>
        <div class="featured-posts-wrapper<?php echo $count; ?> featured-posts-wrapper<?php echo ($count == 7) ? ' no-margin-right' : ''; ?>">
            <a href="<?php the_permalink(); ?>" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" title="<?php the_title_attribute(); ?>"><img id="featured<?php echo $count; ?>" class="featured" alt="<?php the_title_attribute(); ?>" src="<?php echo get_post_meta($post->ID, 'image', true); ?>" /></a>
            <a id="featured-text<?php echo $count; ?>" href="<?php the_permalink(); ?>" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
        </div>
<?php
    endwhile;
    wp_reset_postdata();
?>
</div>
<!-- Featured Posts -->

PS: I’ve included the div tags and classes hoping that they’ll help the clueless. So, first put the code in a template, and check how and what it outputs, to get a better idea.

EXPLANATION:

  • Add the code in any template of your choice (header.php, index.php, home.php, archive.php, search.php, content.php, or any other). That’s where you’ll see the output.

  • Change the number (7) in this line to a number that’s equal to the number of posts you want it to show:

    $some_featured_posts = new WP_Query(array('tag' => 'example2', 'posts_per_page' => 7));
    

    In the above code, the 'tag' => 'example2' says that the latest posts tagged “example2” are to be shown. If you want to have a category instead, use 'category_name' => 'example2'

  • In this line:

    <div class="featured-posts-wrapper<?php echo $count; ?> featured-posts-wrapper<?php echo ($count == 7) ? ' no-margin-right' : ''; ?>">
    

    I use class="featured-posts-wrapper<?php echo $count; ?> so that I can have a different class for each post that’s output. To be specific, the code above outputs as class="featured-posts-wrapper1" for the first post, class="featured-posts-wrapper2" for the second post, and so on.

    On the other hand, <?php echo ($count == 7) ? ' no-margin-right' : ''; ?> allows you to set a specific class for the last entry (as per the example, the 7th post). The code above, adds no-margin-right class to the last post in the output.

  • In this line:

    <a href="<?php the_permalink(); ?>" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" title="<?php the_title_attribute(); ?>"><img id="featured<?php echo $count; ?>" class="featured" alt="<?php the_title_attribute(); ?>" src="<?php echo get_post_meta($post->ID, 'image', true); ?>" /></a>
    

    <?php echo get_post_meta($post->ID, 'image', true); ?> outputs the image URL you assigned to the post using the “image” custom field and its value (an image URL).

  • Rest of the values I used are pretty standard. <?php the_permalink(); ?> outputs the permalink URL, <?php the_title_attribute(); ?> and <?php the_title(); ?> output the title of the post.

Here’s an example of what you can pull off (you can actually do anything):

Example


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment