wordpress纯代码实现站外链接自动增加rel=external,并显示外链图标。让访客更加容易的分辨外部链接,提升用户体验。
具体代码如下:- function url_domain_name($url){
- preg_match("/^(http:\/\/)?([^\/]+)/i", $url, $match);
- $host = $match[2];
- preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $match);
- return $match[0];
- }
- //判断是否为图片链接
- function external_image($url) {
- $chain=strtolower($url);
- if ((strpos($chain, ‘.jpg’) > 0) || (strpos($chain, ‘.gif’) > 0) || (strpos($chain, ‘.png’) > 0))
- {
- return true;
- }
- return false;
- }
- function parse_external_link($match){
- if ( !external_image($match[3]) && (url_domain_name($match[3]) != url_domain_name($_SERVER["HTTP_HOST"])) ){
- if(preg_match(‘/rel="(.*?)"/’, $match[1], $external)){
- $rel = strpos(strtolower($external[1]),"external")?$external[1]:$external[1].’ external’;
- $match[1]=str_replace($external[0],”,$match[1]);
- }else if(preg_match(‘/rel="(.*?)"/’, $match[4], $external)){
- $rel = strpos(strtolower($external[1]),"external")?$external[1]:$external[1].’ external’;
- $match[4]=str_replace($external[0],”,$match[4]);
- }
- $rel=!empty($rel)?’rel="’.$rel.’"’:'rel="external nofollow"’;
- return ‘<a href="’ . $match[2] . ‘//’ . $match[3] . ‘"’ . $match[1] . $match[4] . $rel. ‘>’ . $match[5] . ‘</a>’;
- } else {
- return ‘<a href="’ . $match[2] . ‘//’ . $match[3] . ‘"’ . $match[1] . $match[4] . ‘>’ . $match[5] . ‘</a>’;
- }
- }
- function external_link($url) {
- $pattern = ‘/<a (.*?)href="(.*?)\/\/(.*?)"(.*?)>(.*?)<\/a>/i’;
- $url = preg_replace_callback($pattern,’parse_external_link’,$url);
- return $url;
- }
- add_filter(‘the_content’, ‘external_link’);
- add_filter(‘comment_text’, ‘external_link’)
复制代码 复制以上内容到functions.php文件中
CSS代码:- a[rel~="external"]{padding-right: 16px;background: transparent url("images/link_external.png") 99% 40% no-repeat;}
复制代码 |