0

I have a loop through my custom post types.

I want to select 8 posts only, and print out the output into 2 columns, 4 posts each. I'm not really sure how to approach this. So far I have:

<?php
            $args = array( 'post_type' => 'hh_event', 'posts_per_page' => 8 );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();

                echo '<div class="entry-date">';
                $event_date = get_post_meta($post->ID, 'event_date', true); 
                echo date('M j',strtotime($event_date));
                echo '</div>';
                the_title();
                echo '<div class="entry-content">';
                the_content();
                echo '</div>';

            endwhile;
        ?>

1 Answer 1

1

A simple solution would be to have your content stored in an array like so:

<?php
$args = array( 'post_type' => 'hh_event', 'posts_per_page' => 8 );
$loop = new WP_Query( $args );

$columns = array( '', '' );
$content = '';
$i = 0;
global $post;

while ( $loop->have_posts() ) : $loop->the_post();
    $content = '<div class="entry-date">';
    $event_date = get_post_meta($post->ID, 'event_date', true); 
    $content .= date('M j',strtotime($event_date));
    $content .= '</div>';
    $content .= get_the_title();
    $content .= '<div class="entry-content">';
    $content .= apply_filters( 'the_content', $post->post_content );
    $content .= '</div>';

    $columns[ ($i % 2) ] .= $content;
    $i ++;
endwhile;

echo '<div class="column-left">' . $columns[0] . '</div><div class="column-right">' . $columns[1] . '</div>';

?>

So basically you have an array containing two empty strings. You then assign the content of each column to a variable named $content. You then append the value of that variable to the proper part of the $columns variable and increment the counter $i.

Then just echo the contents of each column to a proper wrapping <div> element, or however you are going to separate those into two columns.

Sign up to request clarification or add additional context in comments.

2 Comments

How would you modify this loop to alternate left column / right column on every post (instead of the first 4 being in the left, then moving on to the right)?
That's the way it should work right now. See the $columns[ ($i % 2) ] .= $content; part? This basically says "add the content to the n array element" where "n" is 0 or 1 and this alters with every cycle. Because you have $i = 0 in the first cycle and 0 % 2 == 0. In the second cycle you have $i = 1 and 1 % 2 == 1. In the third cycle you have $i = 2 and 2 % 2 == 0. And so on. Is it working in a different way for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.