Aslam Doctor

Solution: Extra P and BR tags included while using ACF (Advanced Custom Fields)

Hey Guys, this is something I have been looking for a couple of days. Finally got the solution on my own.

Problem

While using the ACF (Advanced Custom Fields) plugin on a WordPress site, when you add WYSISYG editor field, it stores the custom field data properly without any issues. But when you print that data on front-end, it ends up printing it with extra P and BR tags. This happens mainly when you are using some shortcodes inside this WYSISYG field.

So I tried contacting directly with ACF Support guys and they suggested me to use the below solution.

$section_content = get_field('section_content', false, false);

Please note that section_content is the field name I am using. I tried this solution but what it did is, it simply converted the content into Plain text. But what’s the difference between simple Textarea and WYSIWYG field then?

So I decided to post the issue over our favorite place stackoverflow.com 🙂
I got some answers over there and most of them were suggesting me to use the “the_content” filter as shown in the below code.

$section_content = apply_filters('the_content', $section_content);

Now, this solved the issue partially as it removed some of the extra BR and P tags but still it was not removing the tags that were added before and after the shortcodes, I was using in WYSIWYG field.

Internally, this filter gets applied already while getting the field value. So it got applied twice if we use the above-mentioned code.

Solution

It took a while to understand the issue but the solution was in front of me. I simply combined the solution of ACF support guys and Stackoverflow guys using the below code.

$section_content = get_field('section_content', false, false); 
$section_content = apply_filters('the_content', $section_content);

And that fixed it. So what it did was, converted the whole content into plain text first. And then it applied the the_content filter, so the shortcodes got compiled properly.

If you are facing a similar issue, then make sure to use the above 2 lines before printing/echoing any WYSISYG field. Make sure you change the section_content with your provided field name.

I hope the ACF guys fix this issue in future updates.

If you found this helpful, please share it with others, and don’t forget to leave your comments.