Skip to content

Instantly share code, notes, and snippets.

@billerickson
Last active March 28, 2019 19:59
Show Gist options
  • Save billerickson/1238281 to your computer and use it in GitHub Desktop.
Save billerickson/1238281 to your computer and use it in GitHub Desktop.
Customize Event Query using Post Meta
<?php
/**
* Customize Event Query using Post Meta
*
* @author Bill Erickson
* @link http://www.billerickson.net/customize-the-wordpress-query/
* @param object $query data
*
*/
function be_event_query( $query ) {
if( $query->is_main_query() && !$query->is_feed() && !is_admin() && $query->is_post_type_archive( 'event' ) ) {
$meta_query = array(
array(
'key' => 'be_events_manager_end_date',
'value' => time(),
'compare' => '>'
)
);
$query->set( 'meta_query', $meta_query );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'meta_key', 'be_events_manager_start_date' );
$query->set( 'order', 'ASC' );
$query->set( 'posts_per_page', '4' );
}
}
add_action( 'pre_get_posts', 'be_event_query' );
@tiborp
Copy link

tiborp commented Apr 20, 2013

Hi Bill,

I'm using this query and what I'm trying to solve now is following:

I have events (training) that will be held several times (through the year), so I've set up some extra fields for the extra dates. Since I'm using the 'compare' method, and also need to show the events from wich the first date is in the past, but have a second (or third etc.) date in the future, I am querying all date fields, using 'relation=>OR'. See my code here:

https://gist.github.com/tiborp/5425207.

Problem is that the orderby meta_key is no longer working when using more then one meta key. Any tips on how to accomplish this?

@tiborp
Copy link

tiborp commented Apr 22, 2013

Me stupid...when an end date is set (also for one day events) this is not an issue.

@joshuadavidnelson
Copy link

Bill, you've got a double && in the if statement, FYI. Twice I copied and pasted and forgot to update that ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment