Skip to content

Instantly share code, notes, and snippets.

@nandomoreirame
Created August 19, 2019 02:04
Show Gist options
  • Save nandomoreirame/dd21896d7cd835d1f55b2a9a1d4f41c2 to your computer and use it in GitHub Desktop.
Save nandomoreirame/dd21896d7cd835d1f55b2a9a1d4f41c2 to your computer and use it in GitHub Desktop.
Add custom post meta to WordPress REST API
<?php
function get_custom_post_meta_cb($object, $field_name, $request) {
return get_post_meta( $object['id'], $field_name, true );
}
function get_custom_post_meta_cb_the_content($object, $field_name, $request) {
return apply_filters( 'the_content', get_post_meta( $object['id'], $field_name, true ) );
}
function update_custom_post_meta_cb($value, $object, $field_name) {
if ( ! $value || ! is_string( $value ) ) { return; }
return update_term_meta( $object->ID, $field_name, $value );
}
function api_register_rest_field($post_type, $field_id, $isEditor = false) {
if ( isset( $post_type ) && isset( $field_id ) ) {
if ($isEditor) {
$get_callback = 'get_custom_post_meta_cb_the_content';
} else {
$get_callback = 'get_custom_post_meta_cb';
}
register_rest_field($post_type, $field_id, [
'get_callback' => $get_callback,
'update_callback' => 'update_custom_post_meta_cb',
'schema' => null
]);
}
}
function register_rest_custom_fields() {
api_register_rest_field( 'page', 'about_como_construimos', false );
api_register_rest_field( 'page', 'about_analise_fundamentos', true );
api_register_rest_field( 'page', 'about_estruturacao_fidc', true );
api_register_rest_field( 'page', 'about_revisao_monitoramento', true );
api_register_rest_field( 'page', 'about_valores_text', false );
api_register_rest_field( 'page', 'about_valores_image', false );
api_register_rest_field( 'downloads', 'download_file', false );
}
add_action('rest_api_init', 'register_rest_custom_fields');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment