2

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.

  • By default, your link would looks like this www.domain.com/tag/test2/ as the tag would be test2. The dynamic parameter is set with the data in the URL. The question is relatively unclear. Do you want to create a script that shows posts based on a random tag in all available tags from the website? – Patrice Poliquin Jul 11 '18 at 14:49
  • yes that's what I mean. – Mina Jul 11 '18 at 15:03
0

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; ?>
  • I'm sure you know it, but... you don't need if statement, if there is no else in it in this case :) – Krzysiek Dróżdż Jul 11 '18 at 19:36
  • 1
    I just copied the first example from the docs :) – Jacob Peattie Jul 11 '18 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.