Fix ACF PRO to output unfiltered HTML

Posted by: Alex on March 6, 2024

As promised by ACF many months ago, the latest ACF Pro [6.2.5] update has put the security changes live that stop certain unfiltered HTML snippets from being output/it escapes it and outputs it as a string.

ACF now automatically escapes unsafe HTML when rendered by the_field or the ACF shortcode. We’ve detected the output of some of your fields has been modified by this change, but this may not be a breaking change.

The Error message that ACF Pro is adding to the WordPress dashboard

The ACF Pro article has a few suggestions on the best practices on what to do, however, they’re a little unclear without any specific solutions. Even as a dev—especially if you’re trying to quickly fix a broken site.

So the quick fix, if you’re 100% certain you don’t need to worry about the security implications the ACF update is addressing—is to just change how you output your fields. At a basic level you change from the_field to echo get_field.

Example of how to quickly fix ACF Pro outputting unfiltered HTML:

<?php the_field('my_acf_field_which_has_html_eg_a_form'); ?>

Would become:

<?php echo get_field('my_acf_field_which_has_html_eg_a_form'); ?>

That’s the quick fix, longer term it’s better to lock down your ACF fields and really consider where HTML/scripts should be accepted. In cases where you know HTML/JS/scripts and the like should be output you can use the tweak the following function:

add_filter( 'acf/the_field/allow_unsafe_html', function( $allowed, $selector ) {
    if ( $selector === "google_maps_iframe" ) {
        return true;
    }
    return $allowed;
}, 10, 2);

To make this easier, I’ve created an array logic in the function, so that you can easily list all of your fields that you’d like to allow to use unfiltered HTML.

add_filter( 'acf/the_field/allow_unsafe_html', function( $allowed, $selector ) {
    $allowed_fields = [
        "example_iframe_google_map_embed",
        "my_acf_field_which_has_html_eg_a_form",
        "example_js_embed_codes",
        // ... etc, Add any other field keys you want to allow unsafe HTML for
    ];

    if ( in_array( $selector, $allowed_fields ) ) {
        return true;
    }

    return $allowed;
}, 10, 2);