ORM – Fetching Posts

One of the most common things to do within WordPress is to fetch posts. WP_Query is not the most intuitive of APIs for fetching content, so we have built an Eloquent-like ORM (Object-Relational Mapper) Repository for fetching posts. Within The Events Calendar and Event Tickets, we provide a number of ORM Repositories for our custom post types with helper-functions:

  • tribe_attendees() – Attendee posts
  • tribe_events() – Event posts
  • tribe_organizers() – Organizer posts
  • tribe_tickets() – Ticket posts
  • tribe_venues() – Venue posts

Refer to the ORM – Basics page for more information on how to use the core methods of these repositories.

Basic Usage

We are going to make use of tribe_events() to fetch some events with custom queries and demonstrate the usage of the ORM Repositories.

Top ↑

Fetch events by ID

$result = tribe_events()
	->where( 'id', 5 )
	->first();

Top ↑

Search for events using a search term

$result = tribe_events()
	->search( 'WordPress' )
	->all();

Top ↑

Chaining modifiers

We can do more complex queries by chaining multiple modifiers to get the desired result. The following example will return an array of Event titles which are active in the next 2 weeks.

$result = tribe_events()
	->where( 'starts_after', 'today' )
	->where( 'ends_before', '+2 weeks' )
	->order_by( 'event_date' )
	->order( 'DESC' )
	->pluck( 'post_title' );

Top ↑

Dynamically build queries

We can also keep building our query dynamically to create complex queries similar to the following example. Here, we will paginate the results depending on the conditionals and then fetch the IDs of the matching posts.

$query = tribe_events()->by( 'featured', false );
$paged = 2;

if ( ! empty( $paged ) ) {
  $query->per_page( 5 )->page( $paged );
}

$query->where( 'cost', 'Free' );

$result = $query->get_ids();

Top ↑

Creating, saving, and updating posts

To see details on this, check out the Modifying the database section of ORM – Methods.

Top ↑

Aliases & Schemas

Aliases are helpful…well…aliases to fields and meta. They merely exist to make the API more approachable. Examples: title is an alias for post_titlecost is an alias for _EventCost, etc.

Schemas define how to query posts using meta fields with custom arguments. To get more information on what schemas have been defined, check out the following:

Note: Additional schemas can be found in our other premium plugins.

Top ↑

Simple meta fields

For querying simple meta fields, we can make use of the where() method using a key, value pair.

$result = tribe_events()
	->where( 'all_day', true )
	->all();

Top ↑

Complex meta fields

For querying more complex meta fields, the where() method may accept additional parameters.

$result = tribe_events()
	->where( 'cost_between', 4, 5 )
	->all();