WordPress.org

Ready to get started?Download WordPress

Forums

Dynamic Link from WP_Query (2 posts)

  1. dadvan
    Member
    Posted 1 year ago #

    Hello,

    I need help with pulling in the tag name found by the query in order to create a link to view all the contents of the tag. Please see the code below:

    <?php
    global $post;
    $my_query_args = array(
        'posts_per_page' => 10, // change this to any number or '0' for all
        'post_type' => 'post',
        'tax_query' => array(
            array(
                'taxonomy' => 'post_tag',
                'field' => 'slug',
                'terms' => $post->post_name // this gets the page slug
            )
        )
    );
    // a new instance of the WP_query class
    $my_query = new WP_Query( $my_query_args );
    
    if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
    ?>
    
    <ul>
    <li><a>"><?php the_title() ?></a> <span class="authordate">-Written by <?php the_author() ?> on <?php the_time('m/j/y') ?></span></li>
    </ul>
    <?php endwhile; endif;
    echo "<h2>Displaying $my_query->post_count of $my_query->found_posts Articles</h2>";
    ?>
    <a href="/tag/<?php $my_query->post_name?>">See All Related Articles</a><?php wp_reset_postdata(); ?>
  2. dadvan
    Member
    Posted 1 year ago #

    So I replaced this:

    <a href="/tag/<?php $my_query->post_name?>">See All Related Articles</a>

    With this:

    <a href="/tag/<?php echo $post->post_name; ?>">See All Related Articles</a>

    I also moved it after:

    <?php wp_reset_postdata(); ?>

    Hope this helps someone!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags