Create Your Own Event Scope

Whilst Events Manager 4.0 introduced new event scopes such as events today, tomorrow, this month, next month and more, it still might be that you want something more specific. We can’t predict what everyone will want, but we can certainly make it easy for you to get what you want!

We’ll show you how to create your own scopes by creating a custom “Today and Tomorrow” scope.

add_filter( 'em_events_build_sql_conditions', 'my_em_scope_conditions',1,2);
function my_em_scope_conditions($conditions, $args){
	if( !empty($args['scope']) && $args['scope']=='today-tomorrow' ){
		$start_date = date('Y-m-d',current_time('timestamp'));
		$end_date = date('Y-m-d',strtotime("+1 day", current_time('timestamp')));
		$conditions['scope'] = " (event_start_date BETWEEN CAST('$start_date' AS DATE) AND CAST('$end_date' AS DATE)) OR (event_end_date BETWEEN CAST('$end_date' AS DATE) AND CAST('$start_date' AS DATE))";
	}
	return $conditions;
}

We’re hooking into a standard filter which is called by all the search objects, e.g. EM_Events, EM_Locations, EM_Categories and EM_People in the format of em_object_build_sql_conditions. The $conditions array is an associative array of SQL conditions, and $args represents the array of attributes used to generate this SQL search. In this case, we’re going to replace the ‘scope’ sql condition so that it searches for dates between today and tomorrow.

		$conditions['scope'] = " (event_start_date BETWEEN CAST('$start_date' AS DATE) AND CAST('$end_date' AS DATE)) OR (event_end_date BETWEEN CAST('$end_date' AS DATE) AND CAST('$start_date' AS DATE))";

This is the crucial line where the SQL is modified and returned to the search function that called it.

Now that we’ve created the logic for our new scope, we need to register that scope with Events Manager by adding it to the em_get_scopes filter, which is called by the em_get_scopes function.

add_filter( 'em_get_scopes','my_em_scopes',1,1);
function my_em_scopes($scopes){
	$my_scopes = array(
		'today-tomorrow' => 'Today and Tomorrow'
	);
	return $scopes + $my_scopes;
}

$scopes is an associative array of scopes in Events Manager. You can also remove scopes if you wish by removing the desired items from the $scopes array.