Skip to content

Instantly share code, notes, and snippets.

@heyjones
Last active March 12, 2020 04:57
Show Gist options
  • Save heyjones/2731aaf3e776ef5efe28e455f79fccaa to your computer and use it in GitHub Desktop.
Save heyjones/2731aaf3e776ef5efe28e455f79fccaa to your computer and use it in GitHub Desktop.
Add REST API support to the Events Manager plugin for WordPress.
<?php
/**
* Events Manager REST API
*
* Add REST API support to the Events Manager plugin for WordPress.
*
* https://wordpress.org/plugins/events-manager/
*/
namespace events_manager\rest_api;
/**
* Register the event information in the REST API.
*/
add_action( 'init', __NAMESPACE__ . '\\init' );
function init() {
$meta_fields = array(
'_event_start',
'_event_end',
'_event_timezone',
);
foreach( (array) $meta_fields as $meta_field ) {
register_meta( 'post', $meta_field, array(
'object_subtype' => 'event',
'type' => 'string',
'description' => '',
'single' => true,
'sanitize_callback' => null,
'auth_callback' => null,
'show_in_rest' => true,
) );
}
}
/**
* Enable events in the REST API.
*/
add_filter( 'register_post_type_args', __NAMESPACE__ . '\\register_post_type_args', 10, 2 );
function register_post_type_args( $args, $post_type ) {
if( 'event' === $post_type ) {
$args['show_in_rest'] = true;
$args['supports'][] = 'custom-fields';
}
return $args;
}
/**
* Disable the Gutenberg editor for the custom post type.
*/
add_filter( 'use_block_editor_for_post_type', __NAMESPACE__ . '\\use_block_editor_for_post_type', 10, 2 );
function use_block_editor_for_post_type( $block_editor, $post_type ) {
if( 'event' === $post_type ) {
$block_editor = false;
}
return $block_editor;
}
/**
* Exclude past events from the REST API and order the events by start date.
*/
add_filter( 'rest_event_query', __NAMESPACE__ . '\\rest_event_query', 10, 2 );
function rest_event_query( $args, $request ){
$meta_query = array(
'relation' => 'AND',
array(
'key' => '_event_start',
'value' => date( 'Y-m-d' ),
'compare' => '>=',
'type' => 'DATE',
),
);
if( isset( $request['store'] ) ) {
$meta_query[] = array(
'key' => '_event_start',
'value' => $request['store'],
'compare' => '=',
);
}
$args['meta_query'] = $meta_query;
$args['orderby'] = 'meta_value';
$args['meta_key'] = '_event_start';
$args['order'] = 'ASC';
return $args;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment