Francesca
Francesca

Reputation: 28148

Wrap outputs of a Wordpress query every second item

I think I am pretty close to the solution but I cannot figure out the logic for where I should close the last div.

I have a wordpress query which requests four posts.

I want to wrap every two items in <section class="sponsor-row">

So I have implemented a counter in my query that counts each post, and if it finds two posts have been output it closes the <section> div off.

But I cannot work out how I should work out if the row should be closed again.

Can anyone figure this out? How can I make it wrap every two outputs in <section class="sponsor-row"> ?

if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
                $the_query->the_post();

                $counter = 0;
                echo '<section class="sponsor-row">'; // Opening the section here

                        if ( has_post_thumbnail() ) {
                                $counter++;

                                echo '<div class="grid half">';
                                        echo '<a class="sponsor" href="'.get_the_permalink().'" target="_blank">';
                                        the_post_thumbnail( 'full' );
                                        echo '</a>';  
                                echo '</div>';

                                if ($counter <= 2){
                                        echo '</section>'; // closing the section if two posts
                                        $counter = 0;
                                }
                        }
                }
        }

Full query here: http://pastebin.com/e6RzZLR5

Upvotes: 0

Views: 267

Answers (1)

rob.m
rob.m

Reputation: 10581

if you do if ($counter <= 2){ then it will close it each time it is less or equal 2, which means it will close it twice for each item. You should use if ($counter == 2){ and $counter = 0; should be at the top before the query, otherwise you will set it to 0 each loop.

See comparison in php

Upvotes: 2

Related Questions