Last active
November 11, 2021 07:14
-
-
Save them-es/cb6a1e3bcf477cb8d61aadd3fc05d5a1 to your computer and use it in GitHub Desktop.
Include ACF fields in WP-API response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/