本文實例講述了WordPress給文章圖片自動添加鏈接的方法。分享給大家供大家參考。具體分析如下:
我們會看到有很多的網站我們點擊圖片就會進入當前文件連接了,下面我來給使用wordpress博客的同學也來介紹此種方法,圖片自動鏈接到文章,添加標題和ALT屬性.
直接將下面的代碼添加到主題的 functions.php 文件即可:
復制代碼
代碼如下:function auto_post_link($content) {
global $post;
$content = preg_replace('/<s*imgs+[^>]*?srcs*=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);
global $post;
$content = preg_replace('/<s*imgs+[^>]*?srcs*=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);
最終的輸出結果如下:
復制代碼
代碼如下:<a href="wordpress-view-history.html" title="WordPress 添加文章瀏覽歷史功能" >
<img src="201303521.png" alt="WordPress 添加文章瀏覽歷史功能" />
</a>
<img src="201303521.png" alt="WordPress 添加文章瀏覽歷史功能" />
</a>
關鍵詞自動添加鏈接
還可以再添加一個功能,將文章標簽作為關鍵詞,將文章內的關鍵詞自動加上鏈接,有利于SEO,別人復制的時候,就會留下鏈接了,在上面的函數里繼續添加一段代碼即可:
復制代碼
代碼如下:function auto_post_link($content) {
global $post;
$content = preg_replace('/<s*imgs+[^>]*?srcs*=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);
global $post;
$content = preg_replace('/<s*imgs+[^>]*?srcs*=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);
希望本文所述對大家的WordPress建站有所幫助。
【網站聲明】本站除付費源碼經過測試外,其他素材未做測試,不保證完整性,網站上部分源碼僅限學習交流,請勿用于商業用途。如損害你的權益請聯系客服QQ:2655101040 給予處理,謝謝支持。