每隔n个帖子添加一定类别的帖子

时间:2015-09-30 17:15:54

标签: php wordpress

我有两个包含帖子的数组,$ portfolio_items和$ ad_items。 每三个帖子应该是$ ad_items的帖子。 来自$ ad_items的帖子可以重复,直到显示来自$ portfolio_items的所有帖子。

对于php来说,我是一个新手,所以我很难解决这个问题。指针和提示将不胜感激。 谢谢!

编辑: 我设法解决了这个问题,但我觉得我的代码有点笨拙和臃肿。

<?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 个答案:

答案 0 :(得分:0)

这是典型的modulo task。这是一些伪代码:

for ($i=0; $i<20; $i++) {
    if (($i % 3) == 0) // do sth.
    else // do sth. else or don't do anything at all
}