0

I have made a query which gives me 8 results. I need to show these in 2 columns of 4 items.

This is my query :

         $args = array(
                  'post_type' => 'event',
                  'meta_key' => 'date',
                  'orderby' => 'meta_value_num',
                  'order' => 'ASC',
                  'posts_per_page' => 8,
                  'meta_query' => array(
                      'key'       => 'date',
                      'value'     => date('Y-m-d',strtotime("today")),
                      'compare'   => '>=',
                      'type'      => 'DATE'
                   ),
                );

        $events = new WP_Query( $args );

I tried using array_splice. Example :

        $firstCol = array_slice($events, 0, 4, true);
        $secondCol = array_slice($events, 4, true);

But this does not seem to work. How can I get 2 arrays from my result?

  • WP_Query does return an object. The posts array you'll find in the $posts property. So $events->posts. – Nicolai Dec 30 '16 at 17:55
1

There's no need to split the array, you can just close the first div once you've counted up to four elements of the array.

$args = array(
    'post_type' => 'event',
    'meta_key' => 'date',
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'posts_per_page' => 8,
    'meta_query' => array(
        'key'       => 'date',
        'value'     => date('Y-m-d',strtotime("today")),
        'compare'   => '>=',
        'type'      => 'DATE'
    ),
);

$events = new WP_Query( $args ); 
$count  = 1;

if ( $events->have_posts() ) : ?>
    <div class="column-1">
    <?php while ( $events->have_posts() ) : $events->the_post();
        // YOUR CONTENT
if ( $count == 4 ) { ?>
    </div>
    <div class="column-2">
<?php }

        $count++;
    endwhile;
    wp_reset_postdata();
endif;
?>
</div>
|improve this answer|||||
  • 1
    All WP query objects also have a built-in counter, $events->current_post. – Milo Dec 30 '16 at 17:16
  • Thx both. I used this solution with $events->current_post for post count. – Nanou Ponette Dec 31 '16 at 14:52
  • @milo, I've never used in the built-in counter before. Would start from now on – Tunji Dec 31 '16 at 15:00
0

if i realy understand your question, put the array in a loop and use a variable as counter

$count=0; 
$firstCol=array(); 
$secondCol=array(); 
foreach($events as $event) {
   $count++;
   if($count <= 4 ) {
     array_push($firstCol, $event);
   }
   else {
     array_push($secondCol, $event);
   }
}
|improve this answer|||||
  • I will try this. I was hoping for a "nicer" solution tho. – Nanou Ponette Dec 30 '16 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.