Displaying Posts by tag dynamically in WordPress

How do I come about to display posts related to a random tag? When I click a tag and directed to tag.php page I want all posts related to the previously clicked tag to be displayed. I have seen a lot of example like this:

<?php $args = array(
    'numberposts' => 3,
    'post_status' => 'publish',
    'tag' => 'travel' //how to give a dynamic value
);

but I would want ‘tag’ to be assign dynamically as to whatever tag I click.

1 Answer
1

The tag.php template shouldn’t use a custom query for its posts at all. When you visit the link to a tag the main query is automatically populated with posts that have that tag. In the template you output the main query with the standard loop.

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
        ... Display post content
    <?php endwhile; ?>
<?php endif; ?>

Leave a Comment