看到一些博客,文章页的图片,都是链接到了当前页面,感觉不错,想用在我的网站,于是遍地找插件,竟然没找到,没办法,只能自己动手。
其实实现很简单,只需要通过正则替换文章中的图片,添加链接地址而已。
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);
将这段代码,贴到主题文件的function.php里就行了,文章的图片,会自动添加当前文章页面的链接,大家可以去在悦目网上看看效果
另外,随手又加了一个小功能,将文章标签作为关键词,将文章内的关键词自动加上链接,有利于SEO,别人复制的时候,就会留下链接了。在上面的函数里继续添加一段代码即可。
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属性,应该怎么实现。现在这个方式,就会把所有图片都加上链接的。其实也简单,稍微改一下就实现了,代码如下:
/*-------------------------------------- 自动为第一张图片添加链接地址,其他图片只加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);