Group CPT posts by Custom Field
-
I’ve set up a custom post type for events and on the archive-events.php template, and I am styling the posts in a grid. I’m trying to figure out how to separate the posts so that those in February 2017 will be grouped under an <h5> label that says “February 2017”, and all events in March 2017 will be grouped under an <h5> tag that says “March 2017,” etc.
I used ACF for the custom fields, and right now each event allows for a “Event Month” text field and an ACF date picker field.
Any help would be much appreciated!
Here is a link to the current test page: https://test.cgla.net/events/
Here is the code for my archive-events.php template:
<?php /* * Template Name: Events Archive */ ?> <?php get_header(); ?> <div id="content"> <div id="inner-content" class="wrap cf"> <main class="main" class="m-all t-2of3 d-5of7 cf" role="main" itemscope itemprop="mainContentOfPage" itemtype="https://schema.org/Blog"> <h1 class="archive-title h2"><?php post_type_archive_title(); ?></h1> <?php if( get_field('events_archive_gala_display', 'option') ): ?> <?php get_template_part( 'events-gala' );?> <?php endif; ?> <div class="event-container"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div id="post-<?php the_ID(); ?> event-item" <?php post_class( 'cf' ); ?>> <h4><?php the_title(); ?></h4> <p><?php the_field('event_date'); ?> | <?php the_field('event_start_time'); ?> - <?php the_field('event_end_time'); ?></p> <p><?php the_field('event_description'); ?> <a href="mailto:<?php the_field('event_rsvp_email'); ?>"><?php the_field('event_rsvp_email'); ?></a></p> <h5><?php $categories = get_the_category(); $separator = ' '; $output = ''; if($categories){ foreach($categories as $category) { if($category->name !== 'open to public') { $output .= $category->cat_name.$separator; } } echo trim($output, $separator); } ?> </h5> <?php if( get_field('add_calendar_link') ): ?> <a href="<?php the_field('add_calendar_link'); ?>" class="calendar-link" target="_blank"><span class="plus-icon"><?php get_template_part('library/images/inline', 'plus.svg'); ?></span></a> <?php endif; ?> </div> <?php endwhile; ?> <?php endif; ?> </div> </main> </div> <?php get_footer(); ?>
I used this function to re-order the posts in ascending chronological order based on the event date (ACF date picker field):
//Re-order Events archive posts in ascending chronological order function wpex_order_events( $query ) { // exit out if it's the admin or it isn't the main query if ( is_admin() || ! $query->is_main_query() ) { return; } // order custom post type archives by metafield in ascending order if ( is_post_type_archive('events') ) { $query->set( 'orderby', 'meta_value'); $query->set('meta_key', 'event_date'); $query->set( 'order' , 'ASC' ); return; } } add_action( 'pre_get_posts', 'wpex_order_events');
- The topic ‘Group CPT posts by Custom Field’ is closed to new replies.