将rel属性添加到包含链接的ACF字段

时间:2018-03-12 21:32:08

标签: wordpress advanced-custom-fields

我想为我的所有链接自动添加rel属性(nofollow noopener noreferrer)。 对于内容(the_content),我使用此代码并且效果很好:

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');

为什么此代码不适用于通过ACF插件创建的自定义字段?此代码基于此资源: 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');

2 个答案:

答案 0 :(得分:0)

我使用load_value而不是load_field

// server script to delete all records from model
function deleteAllRecordsFromModel() {
  var allRecords = app.models.MyModel.newQuery().run();
  app.deleteRecords(allRecords);
}

// client script to call server function
google.script.run
  .withSuccessHandler(function() {
     // TODO: Handle success (optional)
  })
  .withFailureHandler(function() {
     // TODO: Handle error (optional)
  })
  .deleteAllRecordsFromModel();

答案 1 :(得分:0)

很难说为什么代码不起作用,可能需要不同的优先级,或者您需要使用不同的movies_t * pmovie;过滤器。

它是否更有意义,因为你有重复的代码,只是在一个函数中实时进行查找替换?

pmovie.title
相关问题