I have added tags to a custom post type, on its $args array using 'taxonomies' => array('post_tag'). Im using the following code on tag.php to loop posts from a certain tag. It works well but pagination wont work fine. When I try to go to page 2, it gives me a 404 error. If I take out the custom query, it wont loop the custom post type posts. How can I fix it?

$term = get_queried_object();
$slugTerm = $term->slug;
$nameTerm = $term->name;
        $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
        $query_args = array(
          'post_type' => 'blog',
          'paged' => $paged,
          'tax_query' => array(
              array (
                  'taxonomy' => 'post_tag',
                  'field' => 'name',
                  'terms' => $nameTerm,
        $query = new WP_Query( $query_args );
        if($query -> have_posts()):while($query -> have_posts()):$query -> the_post();



  <?php endwhile; ?>
  <div class="pagination">
    <?php if(function_exists('wp_pagenavi')) { wp_pagenavi(array( 'query' => $query ) ); } ?>
  <?php endif; ?>

1 Answer 1


One reason this probably isn't working is that you're not defining $nameTerm anywhere, so you're probably not even querying the correct posts for the current tag.

The main reason though is that tag.php should not have a custom query. The main template files in WordPress should be using The Loop to display posts. WordPress has already queried the correct posts.

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <?php endwhile; ?>

    <div class="pagination">
        <?php if ( function_exists( 'wp_pagenavi' ) ) { wp_pagenavi(); } ?>
<?php endif; ?>

This is by far the most common development mistake I see here. If you're learning how to create a theme it's important to follow the official documentation, refer to the default Twenty X themes (eg. Twenty Twenty One), and find a reputable tutorial. If you jump straight to searching for "how to query posts by tag", for example, without checking if that's even something you need to do for the tag.php template, then you're going to get solutions for the wrong problem.

  • Update your question with the code you're using when not using a custom query. A custom query is absolutely not correct, and you need to remove it. Also include information on how you're trying to view this template. Commented Oct 3, 2021 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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