Using the Regular Expression to Replace External Links in WordPr

  • 时间:2020-09-19 10:45:07
  • 分类:网络文摘
  • 阅读:129 次
wordpress-pad Using the Regular Expression to Replace External Links in Wordpress for SEO purposes php regex wordpress

wordpress-pad

Let’s say we want to put a REL=NOFOLLOW on all external links in your wordpress posts/pages, we can add a filter to parse the content using the regular expression replace function e.g. preg_replace_callback.

1
2
3
4
5
6
7
8
9
10
11
add_filter('the_content','add_utm_string',999);
function add_utm_string($content){
  $content = preg_replace_callback('~href\s*\=\s*[\'"](.*)[\'"]~i', function ($matches) {
     $home_url = parse_url(home_url())['host'];
     if (stripos($matches[1], $home_url) === false) {
        return 'href="'.$matches[1] . '?utm_source='. $home_url . '" rel=nofollow';
     }
     return 'href="'.$matches[1].'"';
  }, $content);
  return $content;
}
add_filter('the_content','add_utm_string',999);
function add_utm_string($content){
  $content = preg_replace_callback('~href\s*\=\s*[\'"](.*)[\'"]~i', function ($matches) {
     $home_url = parse_url(home_url())['host'];
     if (stripos($matches[1], $home_url) === false) {
        return 'href="https://helloacm.com/using-the-regular-expression-to-replace-external-links-in-wordpress-for-seo-purposes/'.$matches[1] . '?utm_source='. $home_url . '" rel=nofollow';
     }
     return 'href="https://helloacm.com/using-the-regular-expression-to-replace-external-links-in-wordpress-for-seo-purposes/'.$matches[1].'"';
  }, $content);
  return $content;
}

We add the filter function add_utm_string to the filter the_content. Then we use the PHP preg_replace_callback function that parses the HTML string of the current wordpress post/page, and replaces the hyperlink if it is external.

We use the following to extract the current domain name e.g. helloacm.com of your wordpress site.

1
$home_url = parse_url(home_url())['host'];
$home_url = parse_url(home_url())['host'];

Then, we can exclude our own links. Otherwise, all external links will be added “NOFOLLOW” tag and the ?utm_source query parameter. You of course can customize the links building easily.

The PHP preg_replace_callback function takes the first parameter: Regular Expression Pattern, the second parameter is a call back function when pattern is matched, and the third paramter the original string.

This is a useful tweak for your wordpress template (you can add above PHP function to your theme template functions.php) that enhances your wordpress SEO.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
女性在特殊时期饮食需要注意,不能吃这些食物  此菜肴脆嫩爽口肉香浓郁且色香味俱全,为冬季百吃不厌的佳肴  枸杞子吃法正确才能更好吸收营养,但人在出现状况时最好别吃它  土豆是一种非常普通的蔬菜,但其营养保健价值令人难以置信  大家别忘了喝碗营养丰富的腊八粥,它对女性朋友的好处尤其多  经常吃一点柚子好处多,柚子皮的作用也不少,以后别再浪费啦  牛奶是常见的营养饮品,如果选择不对,既浪费钱还影响健康  香蕉对身体健康有很多好处,教你用香蕉做一道美味粥吧  香菇与洋葱搭配在一起营养全面,使得保健功效会更好  分数的运算古代的分数除法 
评论列表
添加评论