Skip to content

Instantly share code, notes, and snippets.

@bacoords
Last active September 7, 2017 16:01
Show Gist options
  • Save bacoords/3fe47eb914ef146cc6c5db9299aa725a to your computer and use it in GitHub Desktop.
Save bacoords/3fe47eb914ef146cc6c5db9299aa725a to your computer and use it in GitHub Desktop.
/**
* Enable REST API Support for Charitable Campaigns
*
*/
/**
* Register support for post type
*/
function en_enable_campaign_rest_support( $post_type_args ) {
$post_type_args[ 'show_in_rest' ] = true;
$post_type_args[ 'rest_base' ] = 'campaign';
$post_type_args[ 'rest_controller_class' ] = 'WP_REST_Posts_Controller';
return $post_type_args;
}
add_filter( 'charitable_campaign_post_type', 'en_enable_campaign_rest_support' );
/**
* Add REST API support to Campaign Taxonomies.
*/
add_action( 'init', 'en_enable_campaign_taxonomy_rest_support', 25 );
function en_enable_campaign_taxonomy_rest_support() {
global $wp_taxonomies;
//be sure to set this to the name of your taxonomy!
$taxonomy_name = 'campaign_category';
if ( isset( $wp_taxonomies[ $taxonomy_name ] ) ) {
$wp_taxonomies[ $taxonomy_name ]->show_in_rest = true;
// Optionally customize the rest_base or controller class
$wp_taxonomies[ $taxonomy_name ]->rest_base = $taxonomy_name;
$wp_taxonomies[ $taxonomy_name ]->rest_controller_class = 'WP_REST_Terms_Controller';
}
//be sure to set this to the name of your taxonomy!
$taxonomy_name = 'campaign_tag';
if ( isset( $wp_taxonomies[ $taxonomy_name ] ) ) {
$wp_taxonomies[ $taxonomy_name ]->show_in_rest = true;
// Optionally customize the rest_base or controller class
$wp_taxonomies[ $taxonomy_name ]->rest_base = $taxonomy_name;
$wp_taxonomies[ $taxonomy_name ]->rest_controller_class = 'WP_REST_Terms_Controller';
}
}
/**
* Register Campaign meta fields with Rest API (READ ONLY)
*/
add_action( 'rest_api_init', 'en_enable_campaign_meta_fields' );
function en_enable_campaign_meta_fields() {
$fields = array(
'_campaign_description',
'_campaign_end_date',
'_campaign_location',
'_campaign_latitude',
'_campaign_longitude'
);
foreach($fields as $field){
register_rest_field( 'campaign',
$field,
array(
'get_callback' => 'en_campaigns_get_custom_meta',
'update_callback' => null,
'schema' => null,
)
);
}
}
/**
* Helper function to get meta values
*/
function en_campaigns_get_custom_meta( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name, true );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment