Flexible layout; copying first section content across to excerpt on save

Generate an excerpt from your ACF Flexible Content fields for situations where you are not using the standard WordPress content field.


Advanced Custom Fields is a powerful WordPress plugin that gives you the flexibility to fully customise the content editing experience of your WordPress site. Increasingly, developers are building templates that use Flexible Content sections to create highly customised, modular and flexible layouts.

However, in order to ensure that these flexible layouts work seamlessly with some of the functionality we take for granted in WordPress, some modifications may be necessary. One example of this is the excerpt field. We’re used to the excerpt of a post or page being auto-populated based upon the first few lines of the main content field. If we’re using Flexible Content sections and not the content field, however, we’ll need to find a workaround for this.

The solution is to create a function that fires on the save_post hook. This function will loop through the Flexible Content fields and, when it finds the correct layout, create an excerpt from its content. For example, you could be looking for a certain WYWISYG field of a particular layout that you have on every page.

In the example snippet below, we’ve assumed that the Flexible Content field on each page is called sections and that the content we want to generate a snippet from is called centred_content. The code below is also set to run only on Pages, though this is easily changed or expanded to include other post types.


/**
 * Create excerpt from Flexible Content sections
 */

function create_excerpt_from_sections( $post_id, $post, $update ) {

    if (!post->post_type != 'page') return false;

    $sections = get_field('sections', $post_id);

    foreach($sections as $section)
    {

        if ($section['acf_fc_layout'] == 'centred_content')
        {
            $excerpt = wp_trim_words( $section['content'], 55, '' );
            break;
        }

    }

    if (!$excerpt) return false;

    wp_update_post([
        'ID' => $post_id,
        'post_excerpt' => $excerpt,
    ]);

}

add_action( 'save_post', 'create_excerpt_from_sections', 10, 3 );

A lightweight, intuitive WordPress theme to enable flexible developement.

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

Build with Barebones