custom post types - how to pass args for archive.php query?

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 do

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?

Share Improve this question asked Sep 7, 2019 at 19:39 user145078user145078
Add a comment  | 

2 Answers 2

Reset to default 1

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745176730a4615226.html

相关推荐

  • custom post types - how to pass args for archive.php query?

    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 do

    11小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信