25% off ProSNIPC25OFF

ACF: Display Field Value via Shortcode

Registers a [scseed_acf_field name="field_name"] shortcode that outputs a single ACF field value, safely escaped for display.

PHPby SnipCraft
php
<?php
add_shortcode( 'scseed_acf_field', function( $atts ) {
    if ( ! function_exists( 'get_field' ) ) {
        return '';
    }

    $atts = shortcode_atts( [
        'name'    => '',
        'post_id' => null,
        'default' => '',
    ], $atts, 'scseed_acf_field' );

    if ( empty( $atts['name'] ) ) {
        return '';
    }

    $post_id = ! empty( $atts['post_id'] ) ? absint( $atts['post_id'] ) : null;
    $value   = get_field( sanitize_key( $atts['name'] ), $post_id );

    if ( $value === false || $value === null || $value === '' ) {
        return esc_html( $atts['default'] );
    }

    if ( is_array( $value ) ) {
        return esc_html( implode( ', ', $value ) );
    }

    return wp_kses_post( (string) $value );
} );
#acf#custom-fields#display#frontend#shortcode