I’ve created a custom post type called “Events” and I am using Advanced Custom Fields (WordPress plugin) to add custom fields to the posts. One custom field is the date of the event and my goal is to query the posts based on this date (which is stored in the database as “yymmdd”) and only show future events. I’ve gotten close, but can’t seem to figure out how to integrate the filter with the code I’ve already written.
I know that the WordPress Codex has information on this here (http://codex.wordpress.org/Class_Reference/WP_Query) but being a novice with PHP, I’m at a loss as to how to make it work with my custom field data. Here’s the WordPress code:
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// posts for March 1 to March 15, 2010
$where .= " AND post_date >= '2010-03-01' AND post_date < '2010-03-16'";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );
But I’m not sure how to integrate this with my current query or how to use my date field as the query value rather than the post date. Below is what I’ve written so far.
<?php
$args = array(
'post_type' => 'events',
'posts_per_page' => 4,
'meta_key' => 'event_date',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post();
?>
<h1><?php the_title()</h1>
<?php $eventdate = date_create(get_field('event_date')); ?>
<small><?php echo date_format($eventdate,'M d'); ?></small>
<?php endwhile; endif; ?>
I would really appreciate if someone could show me how to add the filter to my query and how to use the custom field meta for the date of the event rather than the post date. I think I’ve given all the information needed but let me know if I missed something. Thanks!
While researching about the meta_query order by find something that really meets as per your needs
I’d try not using a filter but just a modded WP_Query
I’m sure that it can order by
meta_value_num
, so also themeta_value_num
should work out.I did try and tested its working properly with current events with stardate and end date into custom meta box fields.