If I click a random tag I want the tag page to list only 20 posts that is related to that tag and paginate it.
<?php
/**
* The template for displaying Tag Archive pages.
*/
get_header(); ?>
<div id="container">
<div id="content" role="main">
<h1 class="page-title"><?php
printf( __( 'Tag Archives: %s', 'twentyten' ), '<span>' . single_tag_title( '', false ) . '</span>' );
?></h1>
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'orderby' => 'title', 'order' => 'ASC', 'post_type' => 'post', 'posts_per_page' => 20, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post(); ?>
<div <?php post_class() ?>>
<ul><li id="post-<?php the_ID(); ?>"><a href="https://wordpress.stackexchange.com/questions/101549/<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" ><?php the_post_thumbnail(thumbnail); ?></a></ul>
</div>
<?php endwhile; ?>
<?php if (function_exists("pagination")) {
pagination($additional_loop->max_num_pages);
} ?>
</div><!-- #content -->
<?php get_sidebar(); ?>
</div>
<?php get_footer(); ?>
The problem with this code is it’s listing all the posts and not posts that are related to that tag. Can anyone help me fix?
1 Answer
You’re overwriting the main query with a new query where you don’t specify any tag parameters, which is why you’re seeing all posts and not those specific to the tag you’re viewing. The answer-
Do not modify the main query in the template.
There’s almost never a legitimate reason to have to modify the main query this way. Remove the 3 lines starting from $paged =
and ending with $wp_query = new WP_Query($args);
.
Use the pre_get_posts
action to modify any query parameters before the main query is run.
Put the following code in your theme’s functions.php
:
function wpa101549_tag_query( $query ) {
if ( $query->is_tag() && $query->is_main_query() ) {
$query->set( 'posts_per_page', 20 );
}
}
add_action( 'pre_get_posts', 'wpa101549_tag_query' );
This will run before the database is queried, if a tag page is being viewed, and it is the main query.
Additionally, you’ll have to correct your pagination function call. This:
pagination($additional_loop->max_num_pages);
is calling the pagination
function and passing $additional_loop->max_num_pages
, but there is no $additional_loop
defined anywhere in your template. It should be:
pagination($wp_query->max_num_pages);