Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I add data to posts in WordPress that can be retrieved by WP Rest API

Tags:

wordpress

I used Custom Field Suite to add fields to all WordPress posts, but the field data does not show when I retrieve post data through the WP Rest API using /posts on a stand alone site.

Is there a way to add the CFS data so that it is retrieved by wp-json/posts REST calls? It feels like I just need to put a CFS()->get call in the right place. Or just a basic way to add data to posts so they are retrievable in REST calls?

I've added github issues for CFS and WP-API, but any help or direction would be appreciated. Thanks.

like image 709
OJay Avatar asked Jan 18 '26 02:01

OJay


2 Answers

If someone use WP REST API V2, this may help:

adding this to function.php adds CFS for custom post type and standard posts (project in my case)

function cfs_to_json_api($post_response, $post, $context) {
$post_response->data['CFS']=CFS()->get( false, $post->ID, array( 'format' => 'raw' ) );
return $post_response ;
}

add_filter('rest_prepare_project', 'cfs_to_json_api', 12, 3);
add_filter('rest_prepare_post', 'cfs_to_json_api', 12, 3);

IMPORTANT:

True: add_filter ('rest_prepare_post' 'function', 12, 3);

False: add_filter ('json_prepare_post' 'function', 12, 3); //WRONG

If is Custom Post Type: add_filter ('rest_prepare_{$post_type}' 'function', 12, 3);

EXAMPLE: Name post type = product; add_filter ('rest_prepare_product' 'function', 12, 3);

like image 66
Amino Avatar answered Jan 19 '26 19:01

Amino


Most easiest way to add custom fields in the WP Rest API is to used Advance Custom field plugin, with following small plugin extension.

Add Advance Custom Fields to JSON API

like image 45
Amey Avatar answered Jan 19 '26 19:01

Amey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!