PHP loop - wrap every 2 items AND sort html by elements

admin

Administrator
Staff member
I'm working on a custom template for wordpress. In the end, I would like the following setup:

Code:
<div class="post-group-of-2">
    <a id="post1" href="#">Title 1</a>
    <a id="post2" href="#">Title 2</a>

    <p id="description1">Description from post 1</p>
    <p id="description2">Description from post 2</p>
</div>

<div class="post-group-of-2">
    <a id="post3" href="#">Title 3</a>
    <a id="post4" href="#">Title 4</a>

    <p id="description3">Description from post 3</p>
    <p id="description4">Description from post 4</p>
</div>

<div class="post-group-of-2">
    <a id="post5" href="#">Title 5</a>
    <a id="post6" href="#">Title 6</a>

    <p id="description5">Description from post 5</p>
    <p id="description6">Description from post 6</p>
</div>

I have figured out how to wrap every 2 divs in a container, but the order of each group is as follows:

Code:
<div class="post-group-of-2">
    <a id="post1" href="#">Title 1</a>
    <p id="description1">Description from post 1</p>

    <a id="post2" href="#">Title 2</a>
    <p id="description2">Description from post 2</p>
</div>

<div class="post-group-of-2">
    <a id="post3" href="#">Title 3</a>
    <p id="description3">Description from post 3</p>

    <a id="post4" href="#">Title 4</a>
    <p id="description4">Description from post 4</p>
</div>

<div class="post-group-of-2">
    <a id="post5" href="#">Title 5</a>
    <p id="description5">Description from post 5</p>

    <a id="post6" href="#">Title 6</a>
    <p id="description6">Description from post 6</p>
</div>

Since the query is linear, it obviously grabs the anchor tag and from each the first post in the group, then pulls the second 2. So I am wondering if there is a way to achieve the first html code I posted. I'm thinking a main query loop, then two loops within the post container to call the anchor tags first, then the paragraph tags. But I'm not very advanced at php, and I wanted to see if anyone could help point me in a direction.

My current php code:

Code:
<?php $args = array(
        'post_type' => 'post_type',
        'showposts' => 200,
        'orderby' => 'menu_order',
        'order' => 'ASC'
    );
    $customquery = new WP_Query( $args ); ?>


<?php
    $group = 0;
    while ( $customquery->have_posts() ) : $customquery->the_post();


    $ifGroup = ($group % 2) == 0;
    echo $containerStart = $ifGroup ? '<div class="post-group-of-2">' : ''; ?>

    <a href="#"><?php echo $post->post_name; ?></a>
    <p>Description</p>

    <?php echo $containerEND = $ifGroup ? '' : '<div class="clear"></div></div>';
    $group++;
    ?>
<?php endwhile; wp_reset_query(); ?>