Custom ACF Shortcode with Safe HTML Output

A custom shortcode function to display ACF fields with full HTML support and compatibility for arrays, post IDs, and taxonomy terms, bypassing ACF’s native shortcode restrictions.

function acf_field_shortcode($atts) {
    $atts = shortcode_atts(array(
        'field' => '',
        'post_id' => false,
    ), $atts, 'acf');

    if (function_exists('get_field')) {
        $field_value = get_field($atts['field'], $atts['post_id']);

        // If the field is an array (like a select, relationship, or taxonomy field)
        if (is_array($field_value)) {
            $output = [];

            foreach ($field_value as $item) {
                if (is_numeric($item)) {
                    // Check if it's a post ID
                    $post = get_post($item);
                    if ($post) {
                        $output[] = get_the_title($post->ID);
                        continue;
                    }

                    // Check if it's a taxonomy term ID
                    $term = get_term($item);
                    if (!is_wp_error($term) && !empty($term)) {
                        $output[] = $term->name;
                        continue;
                    }
                }

                // If it's not a number, just add the value
                $output[] = $item;
            }

            return wp_kses_post(implode(', ', $output));
        }

        // If it's a single post ID, get the post title
        if (is_numeric($field_value)) {
            $post = get_post($field_value);
            if ($post) {
                return wp_kses_post(get_the_title($post->ID));
            }

            $term = get_term($field_value);
            if (!is_wp_error($term) && !empty($term)) {
                return wp_kses_post($term->name);
            }
        }

        return wp_kses_post($field_value);
    }

    return '';
}
add_shortcode('acf', 'acf_field_shortcode');

Last updated