1

I'm building a WordPress theme that uses the Advanced Custom Fields (ACF plugin). I have the following function via functions.php:

function filter_p_tags( $content ) {
    $content = str_replace( '<p>','<p class="custom__class">', $content );
    return $content;
}
add_filter('the_content', 'filter_p_tags');
add_filter('acf_the_content','filter_p_tags');

The <p> tags via posts and pages are successfully being replaced with <p class="custom__class">. However, my ACF fields are not being filtered. What am I doing wrong here?

It's worth mentioning that the ACF fields in question belong to an options page. Here's how an option field looks within one of my templates.

<?php the_field( 'text', 'option' ); ?>
Ruvee
  • 8,611
  • 4
  • 18
  • 44
Sam
  • 1,401
  • 3
  • 26
  • 53
  • What's the type of your ACF field? Is it a `Wysiwyg`? Is it a `textarea`? Is it a `simple text` field? – Ruvee Sep 01 '21 at 15:47
  • 1
    I've just realised it's a textarea field. This explains why the filter isn't working. Facepalm! – Sam Sep 01 '21 at 16:03
  • Thanks @Ruvee. I've just tried your answer and it doesn't appear to work. – Sam Sep 01 '21 at 16:34

1 Answers1

2

If your ACF field is a textarea, then you would want to use acf/format_value/type=textarea filter hook instead of using acf_the_content which would be applied on wysiwyg.

add_filter('acf/format_value/type=textarea', 'filter_p_tags_acf', 10, 3);

So your entire code would be something like this:

add_filter('the_content', 'filter_p_tags');

function filter_p_tags( $content ) {

    $content = str_replace( '<p>','<p class="custom__class">', $content );

    return $content;

}

add_filter('acf/format_value/type=textarea', 'filter_p_tags_acf', 10, 3);

function filter_p_tags_acf( $value, $post_id, $field ) {

    $value = str_replace( '<p>','<p class="custom__class">', $value );

    return $value;

}


Another way of doing this

Alternatively, as you suggested, we could use acf/format_value/key={$key} filter hook instead of using acf/format_value/type=textarea. Like so:

add_filter('acf/format_value/key=field_abc123456', 'filter_p_tags_acf', 10, 3);

function filter_p_tags_acf( $value, $post_id, $field ) {

    $value = str_replace( '<p>','<p class="custom__class">', $value );

    return $value;

}
Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • 1
    I was literally just about to offer up the same solution, but it still doesn't work. Weird because this is exactly what the ACF documentation suggests. Could this have anything to do with it being an options field? I've tried `` and ``. – Sam Sep 01 '21 at 16:44
  • 1
    Interestingly, I've just tried your snippet with `add_filter('acf/format_value/key=field_abc123456, 'filter_p_tags_acf', 10, 3);` and it works perfectly. For some reason, it's having trouble picking up on textarea fields. – Sam Sep 01 '21 at 16:49
  • 1
    Thanks for taking the time to help me out :) – Sam Sep 01 '21 at 16:52