dongyu9894 2015-09-30 17:15
浏览 51
已采纳

每隔n个帖子添加某个类别的帖子[关闭]

I have two arrays with posts, $portfolio_items and $ad_items. Every third post should be a post from $ad_items. The posts from $ad_items can repeat until all posts from $portfolio_items have been displayed.

I'm kind of a novice when it comes to php, so I'm having a hard time wrapping my head around this problem. Pointers and tips would be greatly appreciated. Thanks!

Edit: I managed to solve it, but I get the feeling that my code is somewhat clumsy and bloated.

<?php
    $counter = 1;
    $rotation = 3;
    $ad_counter = 0;
    $ad_id = array();

    $query1 = new WP_Query(array(
        "post_type" => "post",
        "post_status" => "publish",
        "tax_query" => array(
            array(
                "taxonomy" => "category",
                "field" => "slug",
                "terms" => "test",
                "operator" => "NOT IN"
            )
        )
    ));

    $query2 = new WP_Query(array(
        "post_type" => "post",
        "post_status" => "publish",
        "tax_query" => array(
            array(
                "taxonomy" => "category",
                "field" => "slug",
                "terms" => "test"
            )
        )
    ));

    if($query2 -> have_posts())
    {
        while($query2 -> have_posts()) : $query2 -> the_post();
            array_push($ad_id, get_the_id());
        endwhile;
    }

    if($query1 -> have_posts())
    {
        while($query1 -> have_posts())
        {
            if($counter == $rotation)
            {
                if($ad_counter >= count($ad_id))
                {
                    $ad_counter = 1;
                }
                else
                {
                    $ad_counter++;
                }
                $t = get_post($ad_id[$ad_counter-1]);
                ?>
                <div class="post type-post status-publish format-standard hentry red">
                    <h1> <?php echo $t->post_title; ?> </h1>
                    <p> <?php $t->post_content; ?> </p>
                </div>
                <?php
                $counter = 0;
            }
            else
            {
                $query1 -> the_post();
                get_template_part("template/testpost");
            }
            $counter++;
        }    
        wp_reset_postdata();
    }
?>
  • 写回答

1条回答 默认 最新

  • doukang2003 2015-09-30 17:47
    关注

    This is a typical modulo task. Here is some pseudo code:

    for ($i=0; $i<20; $i++) {
        if (($i % 3) == 0) // do sth.
        else // do sth. else or don't do anything at all
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?