分享

WordPress 文章图片自动添加当前文章链接 | WordPress大学

 microee 2015-03-26
易多云免备案虚拟主机,新用户免费试用15天,一键安装Wordpress,点此查看详情

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

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

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

  1. function auto_post_link($content) {
  2. 	global $post;
  3.         $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);
  4. 	return $content;
  5. }
  6. add_filter ('the_content', 'auto_post_link',0);

最终的输出结果如下:

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

关键词自动添加链接

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

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

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

一样在functions.php添加:

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

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

实测报告

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

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

请尊重我们的辛苦付出,未经允许,请不要转载 WordPress大学 的文章!

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多