自定义wp_query上的Wordpress分页(next_posts_link)未显示

问题描述 投票:3回答:3

有人提出过类似的问题,但我无法弄清楚我想念的是什么!

我有一个自定义类型字段的静态页面,类似于常规存档或类别页面,但我不能让分页工作。 如果我手动转到第2页(即添加到链接... /页面/ 2),我会收到“较新的帖子”链接,但不会显示在较旧的第一页上! next_posts_link()似乎不存在(没有div注入或任何东西)

这是我的代码:

  $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

  $query_args = array (
        'post_type' => 'bb_articoli',
        'meta_key' => 'bb_data-pubblicazione',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
        'posts_per_page' => 2,      //for testing purposes
        'paged' => $paged,
        'meta_query' => array(
            array('key' => 'bb_fonte-pubblicazione',
                  'value' => 2,
                  'compare' => '='
                  )
        )
  );

  $query = new WP_Query($query_args);

    if ( $query->have_posts() ) :
       while ( $query->have_posts()) :
             $query->the_post();
             get_template_part( 'content' , get_post_format());
       endwhile;

     next_posts_link();
     previous_posts_link();

     else :
         get_template_part( 'content', 'none' );
 endif;

任何帮助是极大的赞赏。谢谢 乙

仅供参考:二十二日使用儿童主题

wordpress pagination
3个回答
14
投票

您的解决方案之所以有效,是因为您要覆盖全局$ wp_query变量。更好的解决方案是将$ query-> max_num_pages添加到next_posts_link()。

next_posts_link('« Older Entries', $query->max_num_pages)

其中$ query是新创建的对象的名称。这样就可以保留$ wp_query。


8
投票

好吧,想通了,所以想分享以备将来参考:

由于某些未知原因,如果查询对象被称为$wp_query,则next_posts_link()和previous_posts_link()只能正常工作!

因此,相应地更改查询对象会使整个过程正常工作:

$wp_query = new WP_Query($query_args);

if ( $wp_query->have_posts() ) :
   while ( $wp_query->have_posts()) :
         $wp_query->the_post();
           // do something
   endwhile;

 next_posts_link();
 previous_posts_link();

适合我,但我没有彻底测试过。据我所知,这在任何地方都没有记载,肯定不在法典中。找到答案here in comment 4 by madhavaji

干杯


3
投票

我遇到过同样的问题。我尝试了所有的解决方案,但没有一个帮助我。

所以对于那些无法用上述解决方案解决这个问题的人来说,这就是我所做的:

<?php
    global $wp_query, $paged;

    if( get_query_var('paged') ) {
        $paged = get_query_var('paged');
    }else if ( get_query_var('page') ) {
        $paged = get_query_var('page');
    }else{
        $paged = 1;
    }

    $wp_query = null;
    $args = array(
        'post_type' => array("fashion", "tv", "sport"),
        'orderby'=>'date',
        'order'=>'DESC',
        'posts_per_page' => 5,
        'paged' => $paged
    );
    $wp_query = new WP_Query();
    $wp_query->query( $args );

    while ($wp_query->have_posts()) : $wp_query->the_post();
        /* YOUR CONTENT HERE */
    endwhile;

    next_posts_link('next');
    previous_posts_link('previous');

    wp_reset_query();
?>

重要的是用全局变量启动代码,因为next_posts_link()previous_posts_link()函数正在读取global $paged$wp_query值。

我希望我能帮忙!

© www.soinside.com 2019 - 2024. All rights reserved.