Fall Back to an ACF Options Value When a Field Is Empty
Uses a site-wide default from your ACF options page whenever a post's own field is empty, such as a standard call-to-action text or banner.
Opens WPIDE on
Code
// Post field and the options field with the default.
$wpide_acf_fallback_field = 'cta_text';
$wpide_acf_fallback_option = 'default_cta_text';
add_filter( 'acf/load_value/name=' . $wpide_acf_fallback_field, function ( $value, $post_id ) use ( $wpide_acf_fallback_option ) {
if ( ( null !== $value && '' !== $value && array() !== $value ) || 'options' === $post_id || 'option' === $post_id || is_admin() || ! function_exists( 'get_field' ) ) {
return $value;
}
$default = get_field( $wpide_acf_fallback_option, 'option', false );
return ( null === $default || '' === $default ) ? $value : $default;
}, 10, 2 );
Notes
Set the post field and the options field that holds the default.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.