How to create wordpress page that shows posts with specific tags?

Like the title says, what code would I use on a wordpress page so that it will only show posts that have a specific tag?

Related posts

Leave a Reply

2 comments

  1. I’m pretty sure I always read on here that new WP_Query() is recommended over query_posts. Additionally you can use the Transient API to improve performance on additional queries. Place this in whatever template where you’d like the list to display:

    // Get any existing copy of our transient data
    if ( false === ( $my_special_tag = get_transient( 'my_special_tag' ) ) ) {
        // It wasn't there, so regenerate the data and save the transient
    
       // params for our query
        $args = array(
            'tag' => 'foo'
           'posts_per_page'  => 5,
        );
    
        // The Query
        $my_special_tag = new WP_Query( $args );
    
        // store the transient
        set_transient( 'my_special_tag', $my_special_tag, 12 * HOUR_IN_SECONDS );
    
    }
    
    // Use the data like you would have normally...
    
    // The Loop
    if ( $my_special_tag ) :
    
        echo '<ul class="my-special-tag">';
    
        while ( $my_special_tag->have_posts() ) :
            $my_special_tag->the_post();
            echo '<li>' . get_the_title() . '</li>';
        endwhile;
    
        echo '</ul>';
    
    else :
    
    echo 'No posts found.';
    
    endif;
    
    /* Restore original Post Data
     * NB: Because we are using new WP_Query we aren't stomping on the
     * original $wp_query and it does not need to be reset.
    */
    wp_reset_postdata();
    

    And in your function.php you will need to clear out the transient when things are updated:

    // Create a function to delete our transient when a post is saved or term is edited
    function delete_my_special_tag_transient( $post_id ) {
        delete_transient( 'my_special_tag' );
    }
    add_action( 'save_post', 'delete_my_special_tag_transient' );
    add_action( 'edit_term', 'delete_my_special_tag_transient' );
    
  2. Before the loop, use query_posts function

    query_posts( 'tag=foo' );
    

    This will returns all posts with the assigned tag.

    <?php
    // retrieve post with the tag of foo
    query_posts( 'tag=foo' );
    // the Loop
    while (have_posts()) : the_post();
        the_content( 'Read the full post »' );
    endwhile;
    ?>
    

    You can also use it to return posts with multiple tags

    query_posts( 'tag=foo,bike' );
    

    For further parameters and reference, see
    http://codex.wordpress.org/Class_Reference/WP_Query#Parameters
    http://codex.wordpress.org/Function_Reference/query_posts