I am working on a WordPress site consisting of a custom post type called "events". Each "event" consists of a custom field called "event date". I'd like to organize all the "events" by months based on the "event date" field.

Here's what I mean:

November 2018

December 2018

January 2019

Perhaps there are better optimized ways, but this is how I would do it:

  1. Get all Events by using WP_Query, and sort them by your custom date field
  2. Loop through all of them and create a new multidimensional array
  3. In this array we are grouping all posts by their date (month and year)
  4. And lastly, loop through our new array, to get the dates and events we extracted

Here's the code:

// Edit these values
$custom_post_type  = 'event';
$custom_date_field = 'event_date';
$order             = 'ASC'; // from the oldest to the newest

// query
$the_query = new WP_Query( [
    'post_type'      => $custom_post_type,
    'posts_per_page' => - 1,
    'meta_key'       => $custom_date_field,
    'orderby'        => 'meta_value',
    'order'          => $order,
] );

// We are creating new multidimensional array
$all_events = [];

while ( $the_query->have_posts() ) :

    $date       = strtotime( get_post_meta( get_the_ID(), $custom_date_field, true ) );
    $month_year = date( "F Y", $date );

    $all_events[ $month_year ][] = $the_query->post;


// And to print this:
foreach ( $all_events as $month_year => $events ) : ?>
    <h3><?php echo $month_year ?></h3>
        /** @var \WP_Post $event */
        foreach ( $events as $event ) : ?>
                // post title
                echo $event->post_title;
                // any custom field
                the_field( 'acf_custom_field', $event->ID );
        <?php endforeach; ?>
<?php endforeach; ?>

You can do whatever you want inside the second foreach loop. Edit it as you need.

|improve this answer|||||
  • Perfect! What about showing the custom fields? Let's suppose I'd like to display a custom field by ACF instead of $event->post_title inside of the $events foreach loop. – user2971921 Oct 16 '18 at 10:07
  • @user2971921 Yes, you can easily add whatever content you want. The $event variable will hold the WP_Post object, so you can use all of its attributes and methods. And to access the ACF fields, just add the second parameter to the ACF function the_field( 'acf_field', $post->ID ). – dboris Oct 16 '18 at 10:16
  • 1
    you made my day! – user2971921 Oct 16 '18 at 11:58

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.