admin管理员组文章数量:1415644
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?
2 Answers
Reset to default 1The 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.
本文标签: custom post typeshow to pass args for archivephp query
版权声明:本文标题:custom post types - how to pass args for archive.php query? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745176730a2646273.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论