ORM – Fetching Posts
Topics
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 poststribe_events()
– Event poststribe_organizers()
– Organizer poststribe_tickets()
– Ticket poststribe_venues()
– Venue posts
For the post related ORM available arguments refer to the ORM Base Params page.
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.
Fetch events by ID
$result = tribe_events()
->where( 'id', 5 )
->first();
Search for events using a search term
$result = tribe_events()
->search( 'WordPress' )
->all();
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' );
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();
Creating, saving, and updating posts
To see details on this, check out the Modifying the database section of ORM – Methods.
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_title
, cost
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.
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();
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();