【问题标题】:Get on every 4th post in WordPress loop在 WordPress 循环中的每 4 个帖子上获取
【发布时间】:2018-06-21 13:50:46
【问题描述】:

我目前正在尝试在我的类别页面上创建一个功能,在每 4 个预览帖子中,在该类别中显示一个广告块。

它的工作原理如下:

  1. 发布 1
  2. 发布 2
  3. 发布 3
  4. 发布 4

广告屏蔽

  1. 发布 5
  2. 发布 6

在我的<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

我有以下几点:

<?php $i = 0; ?>
<?php if (post_num ($i%4 == 0)  < (5 - $featured_count)) : echo "this works"; endif ?>

谁能指引我正确的方向

【问题讨论】:

  • 可以在查询中使用偏移量
  • 请发一个例子
  • @Geme - OP 没有标记为 jQuery 或显示 jQuery,不确定该评论有何帮助....
  • @cale_b 查询,不是 jQuery。 tommcfarlin.com/wp_query-offset
  • // WP_Query 参数 $args = array( 'posts_per_page' => '4', ); // 查询 $query = new WP_Query( $args ); // 在这里做广告 // WP_Query 参数 $args = array( 'posts_per_page' => '4', 'offset' => '4', ); // 查询 $query = new WP_Query( $args );

标签: php wordpress loops php-5.3


【解决方案1】:

你或多或少在那里,这是一个简单的例子,只是显示一些任意文本或帖子标题:

<?php
    $counter = 0;

    if (have_posts()) {
        while (have_posts()) {
            $counter++;
            the_post();

            if ($counter % 5 === 0) { 
                echo 'Advert Here!';
            } else {
                the_title();
            }
        }
    }
?>

我没有测试过这个,只是给你一个想法。

编辑:我应该注意,由于您希望在第四个帖子之后插入广告$counter % 4 不会按照您的想法做,如果您想显示四个帖子然后广告,它将被放置在第 5 个“位置”,因此是$counter % 5

【讨论】:

  • 不错的答案。我鼓励您在答案中链接到 modulo 运算符,并 potentially 以提高可读性(我知道这是一种代码风格的偏好)将 mod 运算符包装在括号中以使其更容易阅读:if ( ( $counter % 5) == 0) {....(只需要双等号,不需要三等号,但同样 - 更多代码样式偏好:)
猜你喜欢
  • 2017-04-30
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 2015-06-10
  • 2018-08-20
  • 2010-11-26
  • 1970-01-01
  • 2021-04-25
相关资源
最近更新 更多