【问题标题】:WP Offset Not Working with Foreach loopWP 偏移不适用于 Foreach 循环
【发布时间】:2018-01-08 21:16:34
【问题描述】:

我目前正在使用 wordpress 循环来检索博客文章、标题、特色图片、日期和类别。话虽如此,我正试图从第 5 个降序帖子开始偏移循环,因为前面的 4 个在页面的前面被引用。

我已成功抵消帖子,但似乎无法抓取类别。

<?php
    $post_args = array(
                 'post_type'   => 'post',
                 'post_status' => 'publish',
                 'order'       => 'DESC',
                 'offset'      => 4
                );
    $post_query = new WP_Query($post_args);
    if ($post_query->have_posts() ):
    $count = 1;
    $terms = get_terms( array(
                    'taxonomy'   => 'category',
                    'hide_empty' => true
             ) );
    while ( $post_query->have_posts() ) : $post_query->the_post();
    $feat_img = wp_get_attachment_url( get_post_thumbnail_id() );
?>
<div class="col-sm-3 col-xs-6">
  <div class="featured-img" style="background-image: url(<?php echo $feat_img; ?>)"
    <?php the_date('F j Y', '<h6>', '</h6>'); ?>
    <h3><?php the_title(); ?></h3>
    <div class="category"><?php echo $terms->name; ?></div>
  </div>
</div>

我尝试了一种稍微不同的方法,并且能够使用 foreach 循环获取每个帖子类别,然后是 while 和 if 循环。虽然我成功获得了每个帖子类别,但偏移量不合作。也许是我想多了。这是我的另一个尝试。

<?php
    $terms = get_terms( array(
        'taxonomy' => 'category',
        'hide_empty' => true,
    ) );
    $count = 1;
    foreach ( $terms as $term ) :
    $post_args = array(
        'offset' => 4,
        'post_type' => 'post',
        'order' => 'DESC',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $term->slug  
            )
        ),  
    );
    $post_query = null;
    $post_query = new WP_Query($post_args);
    if ( $post_query->have_posts() ) :

    while ($post_query->have_posts() ) : $post_query->the_post();
    $feat_img = wp_get_attachment_url( get_post_thumbnail_id() );
?>

有人介意帮忙完成这两项任务吗?任何投入将不胜感激。先感谢您。

【问题讨论】:

    标签: php wordpress foreach offset categories


    【解决方案1】:

    您需要将“posts_per_page”设置为 -1 以外的其他值,文档中对此进行了很好的解释

    https://codex.wordpress.org/Class_Reference/WP_Query

    posts_per_page (int) - 每页显示的帖子数(可用 从 2.1 版开始,替换了 showposts 参数)。采用 'posts_per_page'=>-1 显示所有帖子('offset' 参数是 用 -1 值忽略)。如果分页是,则设置“分页”参数 使用此参数后关闭。注意:如果查询在提要中, wordpress 用存储的“posts_per_rss”覆盖这个参数 选项。要重新设置限制,请尝试使用“post_limits”过滤器,或者 过滤 'pre_option_posts_per_rss' 并返回 -1

    【讨论】:

      猜你喜欢
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 2016-11-24
      相关资源
      最近更新 更多