Skip to content

Instantly share code, notes, and snippets.

@them-es
Last active November 11, 2021 07:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save them-es/cb6a1e3bcf477cb8d61aadd3fc05d5a1 to your computer and use it in GitHub Desktop.
Save them-es/cb6a1e3bcf477cb8d61aadd3fc05d5a1 to your computer and use it in GitHub Desktop.
Include ACF fields in WP-API response
<?php
/**
* Include ACF fields in REST API response
*
* Post, Page or Custom Posttype
*/
function my_theme_acf_to_rest_api( $response, $post, $request ) {
if ( ! function_exists( 'get_fields' ) ) {
return $response;
}
if ( isset( $post ) ) {
$response->data['acf'] = get_fields( $post->ID );
}
return $response;
}
add_filter( 'rest_prepare_post', 'my_theme_acf_to_rest_api', 10, 3 );
add_filter( 'rest_prepare_page', 'my_theme_acf_to_rest_api', 10, 3 );
//add_filter( 'rest_prepare_{my_custom_posttype}', 'my_theme_acf_to_rest_api', 10, 3 ); // Custom posttype
/**
* Include ACF fields in REST API response
*
* Userdata
*/
function my_theme_acf_to_user_rest_api( $response, $user, $request ) {
if ( ! function_exists( 'get_fields' ) ) {
return $response;
}
if ( isset( $user ) ) {
$response->data['acf'] = get_fields( 'user_' . $user->ID );
}
return $response;
}
add_filter( 'rest_prepare_user', 'my_theme_acf_to_user_rest_api', 10, 3 );
@them-es
Copy link
Author

them-es commented Nov 11, 2021

This code snippet is no longer required. WP-API Support has been included in the latest Advanced Custom Fields v5.11 release 🎉
https://www.advancedcustomfields.com/blog/acf-5-11-release-rest-api/
https://www.advancedcustomfields.com/resources/rest-api/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment