【问题标题】:Change number of posts on consecutive category pages (Wordpress)更改连续类别页面上的帖子数量(Wordpress)
【发布时间】:2014-10-17 04:56:06
【问题描述】:

我正在尝试将类别页面上显示的帖子数量更改为连续页面(第 2、3 页等)上的更改。因此,第一页显示 7 个帖子,但该类别的第 2、3 和 4 页等每页仅显示 6 个帖子(即当您单击“下一页”以列出较旧的帖子时)。

我知道更改不同类别/存档页面的帖子数量相对简单 - 但这是不同的,因为我希望分页页面具有不同数量的帖子。

有什么想法吗?

【问题讨论】:

  • 你可以使用paged参数来改变帖子的数量,你可能会有分页问题,​​注意。

标签: php wordpress-theming wordpress


【解决方案1】:

这是我最近在 WPSE 上做的一个回答。我做了一些更改以满足您的需求。你可以去看看那个帖子here

第 1 步

如果您已将主查询更改为自定义查询,请将其改回默认循环

<?php

        if ( have_posts() ) :
            // Start the Loop.
            while ( have_posts() ) : the_post();

                ///<---YOUR LOOP--->

            endwhile;

                //<---YOUR PAGINATION--->   

            else : 

                //NO POSTS FOUND OR SOMETHING   

            endif; 

    ?>

第 2 步

使用pre_get_posts 更改主查询以更改类别页面上的posts_per_page 参数

第 3 步

现在,从后端获取posts_per_page 选项集(我假设为6),并设置我们将要使用的offset。那将是1,因为您需要在第一页发布 7 个帖子,在其余部分发布 6 个帖子

$ppg = get_option('posts_per_page');
$offset = 1;

第 4 步

在第一页,您需要将 offset 添加到 posts_per_page 将加起来为 7,才能在第一页获得您的 7 个帖子。

$query->set('posts_per_page', $offset + $ppp);

第 5 步

您必须将您的offset 应用到所有后续页面,否则您将在下一页上重复该页面的最后一个帖子

$offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );
$query->set('posts_per_page',$ppp);
$query->set('offset',$offset); 

第 6 步

最后,你需要从found_posts 中减去你的偏移量,否则你在最后一页的分页会出错,并给你一个404 错误,因为最后一个帖子会因为帖子数不正确而丢失

function category_offset_pagination( $found_posts, $query ) {
    $offset = 1;

    if( !is_admin() && $query->is_category() && $query->is_main_query() ) {
        $found_posts = $found_posts - $offset;
    }
    return $found_posts;
}
add_filter( 'found_posts', 'category_offset_pagination', 10, 2 );

齐心协力

这就是你的完整查询应该进入functions.php的样子

function ppp_and_offset_category_page( $query ) {
  if ($query->is_category() && $query->is_main_query() && !is_admin()) {
    $ppp = get_option('posts_per_page');
    $offset = 1;
    if (!$query->is_paged()) {
      $query->set('posts_per_page',$offset + $ppp);
    } else {
      $offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );
      $query->set('posts_per_page',$ppp);
      $query->set('offset',$offset);
    }
  }
}
add_action('pre_get_posts','ppp_and_offset_category_page');

function category_offset_pagination( $found_posts, $query ) {
    $offset = 1;

    if( !is_admin() && $query->is_category() && $query->is_main_query() ) {
        $found_posts = $found_posts - $offset;
    }
    return $found_posts;
}
add_filter( 'found_posts', 'category_offset_pagination', 10, 2 );

【讨论】:

  • 我正在尝试,但还没有通过输入所描述的代码获得任何乐趣。如上所述,我与循环有一个区别:分页 已放置在循环 '?>' 之后,因为我需要导航控件在一个单独的 div 中。
  • 您遇到的任何具体问题,我都可以为您提供帮助。您尝试在哪个页面/模板上执行此操作
  • 我在 category.php 上使用了二十四(为我自己的目的而修改)
  • 在我的最后一段代码中,我犯了一个复制和粘贴错误,is_home() 应该是is_category()。我已经改正了
  • 好的,谢谢。我已将 category.php 添加到 Pastbin 以防link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
相关资源
最近更新 更多