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?
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:
add_action(
'pre_get_posts',
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.
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.