Custom WordPress Queries – Extending The Events Calendar Plugin

The Events Calendar plugin developed by modern tribe is brilliant plugin that can be used to manage all sorts of event on a WordPress website. This article will demonstrate how to query custom post types using the Events Calendar Plugin.

To Test out the code in this article you need to have “The Events Calendar” Installed, and some test events added to show results.

Using WP_Query

Like most plugins The Events Calendar stores its events as a custom post type called “tribe_events”, this makes it easy for anyone to list all the events using a basic WP_Query call.

Basic WP_Query Usage

Lets start by querying the database for only events from the “tribe_events” post type:

$query = new WP_Query( array( 'post_type' => 'tribe_events' ) );
if ($query->have_posts())
	while ($query->have_posts()) : $query->the_post();
		echo $query->post->EventStartDate;
		echo $query->post->post_title;
		echo $query->post->post_content; 

The previous code will loop through all the received events. You can add specific arguments to the WP_Query to get the relevant events.

Using WP_Query and meta_query

The key meta_query allows you to search using options for post types, the following code will show you how to query events that are happening in the upcoming week.

$query = new WP_Query( array( 'post_type' => 'tribe_events',
	'meta_query' => array(
			'key' => '_EventStartDate',
			'value' => date('Y-m-d', strtotime('+1 week')),
			'compare' => 'date'
) );

Lets break this query down.

	'key' => '_EventStartDate',
	'value' => date('Y-m-d', strtotime('+1 week')),
	'compare' => ' 'date'

This tells wordpress that we want to querya against the field ‘EventStartDate’, with conditions that ‘<’ the value has to be ‘less than’ the date one week from now date(‘Y-m-d’, strtotime(‘+1 week’)).

Liked this article? help spread the word.