I've got this code to work, but being really new to PHP, I don't know if this is proper. I've sorted a CPT loop by a custom date.
- I'm displaying items from most recent (or future date) to oldest
- if the custom date is in the future I display an additional HTML element that says Coming Soon. I've used
strtotime
for the custom date and compared it to today.
I'm most interested in knowing a better method for converting and comparing time, and if this loop is a proper method of using orderby
with a custom date.
get_field()
is from the Advanced Custom Fields WordPress plugin.
<?php
//Loop arguments
$today = date('Ymd');
$args = array(
'post_type' => 'release',
'showposts' => 6,
'meta_key' => 'release_date',
'orderby' => 'meta_value_num', // orderby meta field date
'order' => 'DESC'
);
// query and loop
$release_query = new WP_Query( $args );
// $release_date = get_field('release_date');
while ( $release_query->have_posts() ) : $release_query->the_post();
// don't duplicate featured posts
if ( in_array($post->ID, $do_not_duplicate) ) continue;
update_post_caches( $posts );
?>
<li class="grid large-4 medium-6 small-12 columns">
<div class="cd"
<?php
$image = get_field('cd_cover');
if( !empty($image) ): ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
<?php endif; ?>
<h2>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</h2>
<?php
$cd_date = get_field('release_date');
$release_date = date('Ymd', strtotime($cd_date)); // convert custom date to something manageable?
if ( $release_date > $today ) {
echo '<p class="soon"><span>Coming Soon!</span></p>';
}
?>
</div><!-- /cd -->
</li>
<?php
//release loop ends
endwhile;
// reset
wp_reset_postdata();
?>