How do I call posts with a certain tag?

I use this to call posts:

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$per_page = get_option('to_count_archives');
query_posts("posts_per_page=".$per_page."&paged=".$paged."&cat=".$cat);
if (have_posts())
?>
<?php while (have_posts()) : the_post(); ?>

And it works great for categories. But on archives pages generated for tags it shows ALL posts, not just posts with a specific tag. I am going to creates a separate archives.php and category.php.

Read More

I need to keep the to_count_archives part of the code because it calls the number of posts per page.

I appreciate any help rewriting the code above to work correctly.

Related posts

Leave a Reply

2 comments

  1. It’s because when you call query_posts, you’re overwriting the original query with a new one, you have to get the original query and reset the things you want to change.

    global $query_string;
    $per_page = get_option( 'to_count_archives' );
    query_posts( $query_string . '&posts_per_page=' . $per_page );
    
  2. Why not use WP_Query and do something like:

    // The Query
    $the_query = new WP_Query(  array( 'posts_per_page' => 5, 'tag' => 'THETAG' ) );
    
    // The Loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
        echo '<li>';
        the_title();
        echo '</li>';
    endwhile;
    

    You could also do the same thing for category. I hope I understood the question your code sample above confused me. I just find WP_Query easier to use 🙂