很多朋友喜欢为wordpress文章中的图片添加当前文章链接,这样做有利于网站的seo,增加搜索引挚的友好度。方法其实也很简单,下面就介绍一下这方面的wordpress技巧。
一、自动为文章中的图片添加当前文章链接。
复制下面代码到wordpress主题的 functions.php 文件中:
- 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);
二、文章中的第一张图片自动加链接,而其他图片加alt属性。
复制如下代码到当前主题的 functions.php 模板文件中:
- /*--------------------------------------
- 自动为第一张图片添加链接地址,其他图片只加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);
注意事项:
1、使用效果可以参看本文中的图片。
2.使用此方法后,由于替代了图片的多余属性,可能导致图片的对齐方式失效。
3.如果使用了图片灯箱效果,由于需要将图片链接到原始图片的地址,而此方法则将图片链接到文章,那么灯箱效果就没办法使用,请自行取舍。
如果你还想自动为文章中的标签也添加链接属性,请参考:自动将wordpress文章中的标签设为关键词并添加链接