Orkhan Hasanli
Orkhan Hasanli

Reputation: 786

Adding rel attribute to ACF fields which contains links

I want to automatically add rel attribute (nofollow noopener noreferrer) for all of my links. For content (the_content) I use this code and it works well:

function add_nofollow_content($content) {
    $content = preg_replace_callback(
        '/<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
    function($m) {
        if (strpos($m[1], "md7.info") === false)
        return '<a href="'.$m[1].'" rel="nofollow noopener noreferrer" target="_blank">'.$m[2].'</a>';
        else
        return '<a href="'.$m[1].'" target="_blank">'.$m[2].'</a>';
    },
    $content);
        return $content;
    }
add_filter('the_content', 'add_nofollow_content');

Why did this code not works for custom fields which was created via ACF plugin? This code based on this resource: https://www.advancedcustomfields.com/resources/acf-load_field/

function add_nofollow_acf($field) {
    $field = preg_replace_callback(
        '/<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
    function($m) {
        if (strpos($m[1], "md7.info") === false)
        return '<a href="'.$m[1].'" rel="nofollow noopener noreferrer" target="_blank">'.$m[2].'</a>';
        else
        return '<a href="'.$m[1].'" target="_blank">'.$m[2].'</a>';
    },
    $field);
        return $field;
    }
add_filter('acf/load_field', 'add_nofollow_acf');

Upvotes: 1

Views: 1875

Answers (2)

Xhynk
Xhynk

Reputation: 13870

It's hard to tell why that code isn't working, perhaps it needs a different priority, or you need to use a different acf/ filter.

Would it make more sense, since you have duplicate code, to just do a find-replace in real time in one function though?

function orkhan_nofollow_all( $buffer ){
    $buffer = preg_replace_callback(
        '/<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',

    function($m) {
        if (strpos($m[1], "md7.info") === false)
        return '<a href="'.$m[1].'" rel="nofollow noopener noreferrer" target="_blank">'.$m[2].'</a>';
        else
        return '<a href="'.$m[1].'" target="_blank">'.$m[2].'</a>';
    },
    $buffer);

    return $buffer;
}

add_action( 'template_redirect', function(){
    ob_start();
    ob_start( 'orkhan_nofollow_all' );
});

Upvotes: 0

Orkhan Hasanli
Orkhan Hasanli

Reputation: 786

I use load_value instead load_field

function add_nofollow_acf($field) {
    $field = preg_replace_callback(
        '/<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
    function($m) {
        if (strpos($m[1], "md7.info") === false)
        return '<a href="'.$m[1].'" rel="nofollow noopener noreferrer" target="_blank">'.$m[2].'</a>';
        else
        return '<a href="'.$m[1].'" target="_blank">'.$m[2].'</a>';
    },
    $field);
        return $field;
    }
add_filter('acf/load_value', 'add_nofollow_acf');

Upvotes: 1

Related Questions