Skip to content

Instantly share code, notes, and snippets.

@pgk
Created June 22, 2017 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgk/1dd4ecf4762077522edd4d1a62778564 to your computer and use it in GitHub Desktop.
Save pgk/1dd4ecf4762077522edd4d1a62778564 to your computer and use it in GitHub Desktop.
WordPress Rest API: Adding custom fields to custom post types
<?php
/**
* Register a custom field (using a bit of Mixtape)
*
* @throws WPJM_REST_Exception When bad things happen.
*/
function register_job_listing_custom_fields() {
$env = $this->wpjm_rest_api->environment();
$string_type = $env->type()->definition( 'string' );
$description = __( 'Application email or Url', 'wp-job-manager' );
$builder = new WPJM_REST_Model_Field_Declaration_Builder();
$field_declaration = $builder->named( '_application' )
->dto_name( 'application_email_or_url' )
->description( $description )
->derived( 'wpjm_get_application_meta' )
->typed( $string_type )
->build();
register_rest_field( 'job_listing', $field_declaration->get_data_transfer_name(), array(
'get_callback' => $field_declaration->get_map_from(),
'update_callback' => null, // TODO: updateable derived field declarations?
'schema' => array( $field_declaration, 'as_item_schema_property' ), // Puke: no Callables allowed here! Will file a bug with wp-core.
) );
}
add_action( 'rest_api_init', 'register_job_listing_custom_fields' )
/**
* @return string
*/
function wpjm_get_application_meta() {
global $post;
return get_post_meta( $post->ID, '_application', true );
}
<?php
/**
* Add REST API support to job listings
*/
function register_job_listings_for_rest() {
global $wp_post_types;
$post_type_name = 'job_listing';
if( ! isset( $wp_post_types[ $post_type_name ] ) ) {
return;
}
$job_listings = $wp_post_types[ $post_type_name ];
$job_listings->show_in_rest = true;
$job_listings->rest_base = 'job-listings';
}
add_action( 'init', array( 'register_job_listings_for_rest' ), 25 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment