【问题标题】:Wordpress sticky posts and "posts_per_page" confusingWordpress 粘性帖子和“posts_per_page”令人困惑
【发布时间】:2016-01-18 21:36:41
【问题描述】:

我有一个带有这个参数的自定义循环:

$sticky = count(get_option('sticky_posts'));
$main_loop = array (
    'posts_per_page' => 4 - $sticky
);

我想做以下事情:

  • 1 个置顶帖:我想显示 3 个帖子 + 置顶帖
  • 2 个置顶帖子:我想显示 2 个帖子 + 2 个置顶帖子
  • 3 个置顶帖子:我想显示 1 个帖子 + 3 个置顶帖子
  • 4 个置顶帖子:我只想显示 4 个置顶帖子

但我不会让它工作。目前我有以下情况:

  • 1 个来自 3 个最新帖子(1,2 或 3)的置顶帖子:我有一个置顶帖子 + 2 个帖子
  • 第四个(或更早)帖子(4,5,6 ...)中的 1 个置顶帖子:我有 1 个置顶帖子 + 3 个帖子(如我所愿)
  • 第四个(或更早)帖子(4,5,6 ...)中的 2 个置顶帖子:我有 2 个置顶帖子 + 2 个帖子(我想要它)
  • 第四个(或更早)帖子(4,5,6 ...)中的 3 个置顶帖子:我有 3 个置顶帖子 + 1 个帖子(我想要它)
  • 第四个(或更早)帖子(4,5,6 ...)中的 4 个置顶帖子:我有 4 个置顶帖子 + 3 个帖子(但我想显示最多 4 个帖子)

简而言之:当我粘贴最近 3 个帖子的帖子时,它不起作用,当我坚持超过 3 个帖子时,它不起作用。

这是完整的循环:

<section>
<h2>Aktuelles</h2>
<?php
$sticky = count(get_option('sticky_posts'));
// WP_Query arguments
$main_loop = array (
'posts_per_page' => 4 - $sticky
);

// The Query
$query = new WP_Query( $main_loop );

// The Loop
while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>

<?php endwhile; wp_reset_postdata(); ?>
</section>

【问题讨论】:

  • 抱歉,多个窗口之间的分页令人困惑。请在您的问题中添加您的代码
  • 我添加了循环的代码。

标签: php wordpress sticky


【解决方案1】:

由于我没有找到这个问题的答案,我使用了另一种方法,结合了 2 个循环,始终显示 4 个帖子。诀窍是从第二个循环中减去粘性帖子数。

<?php 
    $sticky = count(get_option('sticky_posts'));
    if ($sticky > 0) { 
?>
<?php   
    // First loop with sticky posts
    $main_loop_s = array (
        'posts_per_page'         => $sticky,
        'post__in' => get_option('sticky_posts'),
    );
    // The Query
    $do_not_duplicate = array();
    $query = new WP_Query( $main_loop_s );
    // The Loop
    while ( $query->have_posts() ) : $query->the_post(); $do_not_duplicate[] = $post->ID; ?>
    <h3><?php the_title(); ?></h3>      
    <?php endwhile;
?>
<?php // stickycheck end 
    } 
?>
<?php 
    $sticky = count(get_option('sticky_posts'));
    if ($sticky < 4) { 
?>
<?php
    $allstickys = 4 - $sticky;
    // Second loop with rest of posts up to 4
    $main_loop_ns = array (
        'posts_per_page'         => $allstickys,
        'offset'                 => $sticky,
        'post__not_in'           => $do_not_duplicate
    ); 
    // The Query
    $query = new WP_Query( $main_loop_ns );
    // The Loop
    while ( $query->have_posts() ) : $query->the_post(); ?>
        <h3><?php the_title(); ?></h3>          
    <?php endwhile; wp_reset_postdata();
?>
<?php // stickycheck end 
    } 
?>

【讨论】:

    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 2022-01-21
    • 2022-01-17
    • 2018-02-26
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多