WordPress JSON Rest Api Add Custom Fields

8 Feb
2018

Open wp-includes/functions.php file and add:

    function custom_field_get_post_meta_cb($object, $field_name, $request){
			// return get_post_custom();

		$metas = get_post_custom($post_id);

		foreach($metas as $key => $value) {
			if(sizeof($value) == 1) {
			  $metas[$key] = $value[0];
			}
		}
		return $metas;			
    }
    function custom_field_update_post_meta_cb($value, $object, $field_name){
      return update_post_meta($object['id'], $field_name, $value); 
    }
    add_action('rest_api_init', function(){
      register_rest_field('post', 'custom_fields', array('get_callback' => 'custom_field_get_post_meta_cb')); 
    
    });
Be Sociable, Share!

2 Responses to WordPress JSON Rest Api Add Custom Fields

Avatar

Romain

June 29th, 2018 at 14:05

in order to create and update new custom fields, you need the following code :

function custom_field_get_post_meta_cb($object, $field_name, $request){
// return get_post_custom();

$metas = get_post_custom($post_id);

foreach($metas as $key => $value) {
if(sizeof($value) == 1) {
$metas[$key] = $value[0];
}
}
return $metas;
}

function custom_field_update_post_meta_cb($value, $object, $field_name) {
$postId = $object->ID;

//return update_post_meta($postId, $field_name , $value);

foreach ($value as $key => $Data) {
update_post_meta($postId, $key , $Data);
}
}
add_action(‘rest_api_init’, function(){
register_rest_field(‘post’, ‘custom_fields’, array(
‘get_callback’ => ‘custom_field_get_post_meta_cb’,
‘update_callback’ => ‘custom_field_update_post_meta_cb’,
‘schema’ => null,
)
);

});

Avatar

Adel

February 14th, 2020 at 16:45

Hello my friends i need help you in this link :

https://github.com/wp-net/WordPressPCL/issues/190

Please help me . Thx

Comment Form

top