WordPress: layout broken by unexpected HTML tags in ACF fields
A layout looks perfect on localhost but is broken on the staging or production server. The template code is the same, Git is in sync. The culprit is often invisible: a content editor copied text from another website or a Word document and pasted hidden HTML (<div> wrappers, inline styles, empty <p> elements) straight into an ACF WYSIWYG field.
Problem: A layout works correctly on localhost but is broken on staging or production. Inspecting the page shows that an ACF field outputs unexpected <div> wrappers, inline styles or empty <p> tags. An unclosed <div> in the content is enough to break everything below it.
Option 1: plain text fields
If the field should contain plain text only, remove all tags on output and escape the result:
echo esc_html( wp_strip_all_tags( get_field( 'content' ) ) );
wp_strip_all_tags() also removes the content of <script> and <style> tags, which PHP’s strip_tags() leaves behind as text. Better still, change the field type from WYSIWYG to Text or Textarea, so there is nothing to strip.
Option 2: allow only a few tags
When you need to keep some formatting (links, bold, italic) but drop the wrappers, use wp_kses() with a whitelist:
$allowed = array(
'a' => array( 'href' => array(), 'title' => array(), 'target' => array() ),
'strong' => array(),
'em' => array(),
'br' => array(),
'p' => array(),
);
echo wp_kses( get_field( 'content' ), $allowed );
Everything that is not in the list, including style attributes and <div> tags, is removed, while the text inside them stays.
Option 3: remove only specific tags
To strip <div> wrappers and empty paragraphs but keep everything else:
function strip_layout_tags( $content ) {
// Remove opening and closing div tags, keep their content.
$content = preg_replace( '#</?div[^>]*>#i', '', $content );
// Remove empty paragraphs (only whitespace or inside).
$content = preg_replace( '#<p[^>]*>(\s| )*</p>#i', '', $content );
return $content;
}
echo strip_layout_tags( get_field( 'content' ) );
Clean the field once, for every template
Instead of wrapping every get_field() call, clean the value with the acf/format_value filter. It runs every time ACF returns the field, so all templates get clean content automatically:
add_filter( 'acf/format_value/name=content', 'helloadmin_clean_acf_content', 20, 3 );
function helloadmin_clean_acf_content( $value, $post_id, $field ) {
return is_string( $value ) ? strip_layout_tags( $value ) : $value;
}
Priority 20 runs after ACF’s own formatting of WYSIWYG fields (adding paragraphs and running shortcodes). You can also reduce the problem at the source: in the field settings, set the WYSIWYG toolbar to “Basic” and turn off “Show Media Upload Buttons”, so editors have fewer ways to paste complex markup.