admataz
3/10/2017 - 4:55 PM

Adding a support to WP REST API for custom fields

Adding a support to WP REST API for custom fields

<?php
function my_custom_fields_rest_support( $post ) {
        $custom = get_post_meta($post['id']);
        $fields = array();
          foreach($custom as $key=>$value) {
            // Assuming Types  - could be other Custom Field Types
              if(substr($key, 0, 5) == 'wpcf-'){ 
                $fields[str_replace('wpcf-', '', $key)] = $value;
              }
          }
        return $fields;
    }

add_action('rest_api_init', function(){
  register_rest_field('factcheck-resource', 'fields', array('get_callback' => 'my_custom_fields_rest_support'));
});

  
/**
 * Add REST API support to an already registered taxonomy.
 */
function my_custom_taxonomy_rest_support() {
  global $wp_taxonomies;
  $taxonomies = array('resource-country', 'resource-topic');
  foreach($taxonomies as $t){

    if ( isset( $wp_taxonomies[ $t ] ) ) {
      $wp_taxonomies[ $t ]->show_in_rest = true;
    }
  }
}
add_action( 'init', 'my_custom_taxonomy_rest_support', 25 );