airesvsg / acf-to-rest-api

Exposes Advanced Custom Fields Endpoints in the WordPress REST API
https://wordpress.org/plugins/acf-to-rest-api/
1.32k stars 111 forks source link

Get the type of field #365

Open robtoll opened 3 years ago

robtoll commented 3 years ago

Using the REST API returns the field values, but no extra information about the field. It would be really useful to know what type of field it is too (image, radio, single line). I couldn't work out how to do this. Does this already work?? Thanks

robtoll commented 3 years ago

No worries, I worked it out.

Anyone else who might also be stuck on this should set up a custom rest endpoint for acf-field post types. You can match up the acf keys from pages or posts with the acf-field posts.

This function is handy. Probably not the best way to do it, but whatever! Stick it at the bottom of your functions.php file - in the theme youre using. It just grabs all custom fields, not very efficient so refine as needed...

function getCustomFields() { $posts = get_posts(array( 'post_type' => 'acf-field', 'numberposts' => -1, 'fields' => array('ID', 'post_content', 'post_excerpt') ));

if ( empty( $posts ) ) {return null;}

$customFields = [];

foreach($posts as $post){ array_push($customFields, array("ID"=>$post->ID, "title"=>$post->post_title, "slug"=>$post->post_excerpt, "config"=>unserialize($post->post_content))); }

return $customFields; }

add_action( 'rest_api_init', function () { register_rest_route( 'wp/v2', '/customFields', array( 'methods' => 'GET', 'callback' => 'getCustomFields', 'permission_callback' => '__return_true' ) ); } );