Adding a post of certain category every nth post

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!

Read More

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();
    }
?>

Related posts

1 comment

  1. 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
    }
    

Comments are closed.