Include Advanced Custom Fields Flexible Layout content in the REST API

If you’re using Advanced Custom Field’s powerful Flexible Layout fields to create modular WordPress templates then you may find you need to include this content in the REST API output.

Using WordPress’ register_rest_field() function, we can register a new field in the response to the ‘page’ endpoint using the snippet below. The following code targets the ‘page’ endpoint but this value can be easily changed to ‘post’ or any custom post type. Since the first argument of the register_rest_field() function also accepts an array, you can even target multiple post types with this one snippet.

function register_rest_field() {

    register_rest_field( ['page'],
            'get_callback'    => 'get_rest_flexiblecontent',
            'update_callback' => null,
            'schema'          => null,


 add_action('rest_api_init', 'register_rest_field' );

Once we’ve registered our new ‘flexiblecontent’ field, we need to create the callback function that will populate it with content from our Flexible Layout fields. The get_rest_flexiblecontent() function below will loop through a Flexible Layout field called sections and add a field called content to the ‘flexiblecontent’ field. The name of this field can of course be changed to suit your own requirements and you can also create conditional arguments to return different fields for each layout type.

 function get_rest_flexiblecontent( $object, $field_name, $request ) {
    $post = get_post( $object['id'] );

    $sections = get_field( 'sections', $post->ID );

    $content = '';

    foreach($sections as $section)
    	$content .= $section['content'];

    return $content; 


A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones