Create Events Use Case Examples

Following the CRUD operation standards, the create() functionality of the ORM allows developers to effortlessly add new calendar events programmatically. This guide will start with basic examples and work our way up to more dynamic and complex scenarios.

Basic Usage

Top ↑

Minimum Requirements

When using the ORM to programmatically create events, the only arguments that are required are a title and when the event will occur. Arguments are formatted in an array in key, value pairs.

$result = tribe_events()
	->set_args( [ 
		'title'   => 'Programmatically Created Event',
		'all_day' => 'true'
		])
	->create();

Top ↑

Adding Arguments

Once you start adding more details when creating an event, it can be helpful to pull the arguments array into a separate variable.

$args = [
	'title'           => 'BBQ',
	'start_date'      => '+2 weeks 10:00:00',
	'end_date'        => '+2 weeks 12:00:00',
	'cost'            => 14.99,
	'currency_symbol' => '$',
	'status'          => 'publish',
];

$result = tribe_events()->set_args( $args )->create();

Top ↑

Advanced Usage

Top ↑

Recurring Events

For creating a recurring event with the ORM you can use the recurrence argument, which follows the iCalendar RRULE format. You can use this tool if you are unfamiliar with this format. Compatibility with the iCalendar standard is one of the new features of the CT1 implementation and it can be used to replace the verbose recurrence format used in the _EventRecurrence post meta, if preferred. These events will automatically be added to a new Series with the same title as the events.

$args = [
	'title'      => 'Weekly Book Club',
	'start_date' => '2024-01-01 17:00:00',
	'end_date'   => '2024-01-01 20:00:00',
	'status'     => 'publish',
	'recurrence' => 'RRULE:FREQ=WEEKLY;COUNT=10',
];

$result = tribe_events()->set_args( $args )->create();

Top ↑

Conditional and Dynamic Event Creation

You can combine the ORM querying and creation abilities to add checks before creating an event. For example, let’s say at the beginning of each week you wanted to create an event for ‘Office Hours’, but only if there is not already an event with the same title. This example also includes dynamically adding the date and time of the event upon creation.

$existing_events = tribe_events()
    ->where( 'starts_after', 'yesterday' )
    ->where( 'ends_before', '+1 week' )
    ->where( 'title', 'Office Hours' )
    ->count();

if ( ! $existing_events ) {
    $current_time = current_time( 'Y-m-d H:i:s' );
    $start_time   = date( 'Y-m-d H:i:s', strtotime( $current_time . ' +1 hour' ) );
    $end_time     = date( 'Y-m-d H:i:s', strtotime( $start_time . ' +2 hour' ) );

    $args = [
        'title'      => 'Office Hours',
        'start_date' => $start_time,
        'end_date'   => $end_time,
        'status'     => 'publish',
    ];

    $result = tribe_events()->set_args( $args )->create();
}