Using an ACF field value as a fallback for WordPress post excerpt

WordPress’ the_excerpt() and get_the_excerpt() functions are handy template utilities for displaying a short sample of a post as these will check for an explicit excerpt before falling back to a truncated version of the post content.

In the work that I do, we often have post types that don’t necessarily have post content or an excerpt field — many of the post types we create are simply an ACF field group with the exact data points relative to the project at hand. This approach gives the user a very clean, precise interface and also makes it easy for us to use custom database tables where we are expecting a lot of data and want the performance benefits and flexibility that normalisation offers.

When rendering these post types on the front end, it’s not uncommon for us to reuse template partials from other contexts. Sometimes we hit the situation where the partial is using WordPress’ excerpt functions and because we are using purely ACF fields, that function call results in an empty string.

Fortunately, WordPress’ excerpts are filterable which makes it very easy to inject a value from an ACF field. The following code snippet demonstrates the scenario where an ACF field is used as the excerpt where an excerpt doesn’t already exist. This ensures that a defined excerpt will have precedence over the ACF field.

add_filter( 'get_the_excerpt', function ( $excerpt, $post ) {
if ( ! empty( $excerpt ) ) {
return $excerpt;
// On a specific post type, use an ACF field value as the excerpt.
if ( $post->post_type === 'my_custom_post_type' ) {
$excerpt = get_field( 'product_description', $post->ID );
return $excerpt;
}, 10, 2 );

About the author

Phil Kurth is a web developer living in Melbourne, Australia. Phil has a long history of WordPress development and enjoys building tools to empower others in their web design/development practice.

When not working with the web, Phil is usually spending time with his two young sons or is out hiking through the Australian bush.

Posted by in WordPress Tutorials tagged

Good dev stuff, delivered.

Product news, tips, and other cool things we make.

We never share your data. Read our Privacy Policy

© 2016 – 2024 Hookturn Digital. All rights reserved.