百度 | 神马 | 搜狗 | 技术文档 | 学习资料分享 - 记录帝国CMS及运维技术的点点滴滴
你的位置:首页 > 实用IT技术 » 正文

【站长工具】WordPress 文章图片自动添加当前文章链接

发布时间:2020-09-17

作品分类:站长工具  添加  链接  图片  文章  添加  链接  图片  WordPress

应 @李辉 朋友的要求,分享一下为WordPress文章的图片自动添加当前文章链接的方法,需要的朋友就自己折腾吧。

图片自动链接到文章,添加标题和ALT属性

直接将下面的代码添加到主题的 functions.php 文件即可:

1
2
3
4
5
6
function auto_post_link($content) {
	global $post;
        $content = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', "<a href=\"".get_permalink()."\" title=\"".$post->post_title."\" ><img src=\"$2\" alt=\"".$post->post_title."\" /></a>", $content);
	return $content;
}
add_filter ('the_content', 'auto_post_link',0);

最终的输出结果如下:

1
2
3
<a href="https://www.wpdaxue.com/wordpress-view-history.html" title="WordPress 添加文章浏览历史功能" >
<img src="https://static.wpdaxue.com/img/2013/03/wpdaxue.com-201303521.png" alt="WordPress 添加文章浏览历史功能" />
</a>

关键词自动添加链接

还可以再添加一个功能,将文章标签作为关键词,将文章内的关键词自动加上链接,有利于SEO,别人复制的时候,就会留下链接了。在上面的函数里继续添加一段代码即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function auto_post_link($content) {
		global $post;
        $content = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', "<a href=\"".get_permalink()."\" title=\"".$post->post_title."\" ><img src=\"$2\" alt=\"".$post->post_title."\" /></a>", $content);
 
	    $posttags = get_the_tags();
	 if ($posttags) {
		 foreach($posttags as $tag) {
			 $link = get_tag_link($tag->term_id); 
			 $keyword = $tag->name;
	   		$content = preg_replace('\'(?!((<.*?)|(<a.*?)))('. $keyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s','<a href="'.$link.'" title="'.$keyword.'">'.$keyword.'</a>',$content,2);//最多替换2个重复的词,避免过度SEO
		 }
	 }
	   return $content;
}
add_filter ('the_content', 'auto_post_link',0);

第一张图片加链接,其他图片加alt属性

一样在functions.php添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*--------------------------------------
自动为第一张图片添加链接地址,其他图片只加alt属性,不加链接
默认链接地址为当前文章的链接,alt属性为当前文章的标题
通过修改判断语句if($count==1),可以为指定顺序图片添加链接,不局限于第一个图片
--------------------------------------*/
$count = 0;
function auto_image_handler($matches){
	global $count,$post;
	$count++;
	if($count==1){//第一个图片添加链接地址
		return "<a href=\"".get_permalink()."\" title=\"".$post->post_title."\" ><img src=\"$matches[2]\" alt=\"".$post->post_title."\" /></a>";
	}
	else{//其他图片添加alt属性
		return "<img src=\"$matches[2]\" alt=\"".$post->post_title."\" /></a>";
	}
}
function auto_post_link($content){
	$content = preg_replace_callback('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',
	'auto_image_handler',$content);
	return $content;
}
add_filter ('the_content', 'auto_post_link',0);

参考资料:http://zhaokaihua.com/405.html

实测报告

1.使用上面的代码后,由于替代了图片的多余属性,将导致图片的对齐方式失效;

2.由于使用图片灯箱效果时,需要将图片链接到原始图片的地址,如果使用该方法将图片链接到文章,那么灯箱效果就没办法使用,请自行取舍。

Top