I am trying to pass args to archive.php so that I can order the posts, set the number of posts, etc..

but the query is done like this

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

if it wasnew \WP_Query($args); i was able to pass the args here but this can't be done in archive.php template?


The pre_get_posts hook can be used to modify queries before they're run. You can use $query->set() to set arguments on the WP_Query object, and $query->is_main_query() in the callback to limit your changes to the main query:

    function( $query ) {
        if ( ! is_admin() && $query->is_main_query() ) {
            $query->set( 'posts_per_page', 12 );

You can't target specific templates, but if you want the change to only affect archives, you can use $query->is_archive(), which will be true for date, taxonomy and post type archives, or if you only want to apply the changes to the category archives, you can use $query->is_category(). Many of the normal conditional functions are available as methods for checking the current query.

|improve this answer|||||
  • thank you. Just having doubt in default how WordPress decides the order for its archives? – Latheesh V M Villa Sep 8 '19 at 10:38
  • 1
    Everything’s ordered by date by default. Same as the normal blog. – Jacob Peattie Sep 8 '19 at 12:37

this is the code from my archive.php file:

$args = array( 
    'posts_per_page' => 3,
    'order' => 'DESC'

$myposts = new WP_Query($args);

<?php if ( $myposts->have_posts() ) : ?>

    <?php while ( $myposts->have_posts() ) : $myposts->the_post(); ?>

    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>

<?php else: ?>

    //If there is no post for this category / tag

<?php endif; ?>

I hope I understood the question well and that I can help you.

Best regards.

|improve this answer|||||
  • yes. but how can i pass args to this query? Say if i wanted to order them by title and show only 3 posts with pagination? – Latheesh V M Villa Sep 7 '19 at 19:52
  • I updated the answer, could this work for you? – Matteo Feduzi Sep 7 '19 at 19:56
  • if you change it like that it will become a new loop. archive.php will show the same result for all archives. – Latheesh V M Villa Sep 7 '19 at 19:59
  • Can you better explain the result you would like to achieve? Unfortunately I don't understand English very well. – Matteo Feduzi Sep 7 '19 at 20:00
  • you can't put new WP_Query($args); in archive.php it works without it. I am just checking if there is any method to pass $args to this loop. – Latheesh V M Villa Sep 7 '19 at 20:03

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.