Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Created April 5, 2020 04:30
Show Gist options
  • Save LeanSeverino1022/a03ab30dda8e31007022e47f230a3c84 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/a03ab30dda8e31007022e47f230a3c84 to your computer and use it in GitHub Desktop.
[Modify Query based on Post Meta] #wordpress

This example is a little more complex. We want to make some more changes to our Event post type. In addition to changing the posts_per_page, we want to only show upcoming or active events, and sort them by start date with the soonest first.

I’m storing Start Date and End Date in postmeta as UNIX timestamps. With UNIX timestamps, tomorrow will always be a larger number than today, so in our query we can simply make sure the end date is greater than right now.

Here’s more information on building Custom Metaboxes. My BE Events Calendar plugin is a good example of this query in practice.

If all the conditions are met, here’s the modifications we’ll do to the query:

Do a meta query to ensure the end date is greater than today Order by meta_value_num (the value of a meta field) Set the ‘meta_key’ to the start date, so that’s the meta field that posts are sorted by Put it in ascending order, so events starting sooner are before the later ones

/**
 * 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' );

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