Order Posts by Two Dates in Custom Fields

The below is used to check between two date fields and display only the items that fall within that parameter.

This is also using the Shortcode function so I can place it anywhere in Gutenberg and maintain the template.

<?php function events_function($atts, $content = null) { 
	ob_start(); 
	extract(shortcode_atts(array( 
	'posts_per_page' => '-1', 
	'title' => '' ),$atts)); 
	
	global $post; 
	
	$start = date('Ymd', strtotime("now")); 
	$end = date('Ymd', strtotime("+12 months")); 
	
	$options = array( 
		'posts_per_page' => $posts_per_page, 
		'post_type' => 'event', 
		'post__not_in' => array( $post->ID ), 
		'meta_query' => array( 
			'relation' => 'OR', // check to see if end date has been set 
			array( 
				'key' => 'event_start_date', 
				'compare' => 'BETWEEN', 
				'type' => 'numeric', 
				'value' => array($start, $end), 
			), // if no end date has been set use start date 
			array( 
				'key' => 'event_end_date', 
				'compare' => 'BETWEEN', 
				'type' => 'numeric', 
				'value' => array($start, $end), 
			) 
		), 
		'orderby' => 'meta_value_num', 
		'order' => 'ASC', 
	); 
	
	$artifact = new WP_Query($options); 
	
	if ($artifact->have_posts()) : ?> 
		<?php if($atts['title']) { ?> 
			<h2 class="artifacts-header"><?php echo $atts['title']; ?></h2> 
		<?php } ?> 
		
		<div id="artifact_wrap" class="grid"> 
			<?php while($artifact->have_posts()) : $artifact->the_post(); 
				//the_field('event_start_date'); 
				$large = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'large' ); 
				$medium = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'medium' ); ?> 
				
				<div class="artifact_item"> 
					<a href="<?php the_permalink(); ?>">
						<div> 
							<div class="artifact_image_wrap"> 
								<div class="artifact_image" style="background-image: url(<?php echo $medium[0]; ?>);"></div> 
							</div> 
							<div class="artifact_content"> 
								<div class="artifact_content_inner"> 
									<h3 class="artifact_title"><?php the_title(); ?></h3> 
									<?php the_excerpt(); ?> 
									<div class="wp-block-button is-style-default"> 
										<span class="wp-block-button__link has-white-color has-light-brown-background-color">LEARN MORE</span> 
									</div>
								</div> 
							</div>
						</div>
					</a>
				</div> 
			<?php endwhile; ?> 
		</div><!-- #artifact_wrap --> 
		
		<a href="javascript:void(0);" id="showMore"> </a> 
		
	<?php endif; ?> 
	
	
	
	<?php return ob_get_clean(); 
		
} 
add_shortcode('public_events', 'events_function');

Source.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.