雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

WordPress

當(dāng)前位置:主頁 > CMS教程 > WordPress >

WordPress給文章圖片自動(dòng)添加鏈接的方法

來源:本站原創(chuàng)|時(shí)間:2020-01-11|欄目:WordPress|點(diǎn)擊:

本文實(shí)例講述了WordPress給文章圖片自動(dòng)添加鏈接的方法。分享給大家供大家參考。具體分析如下:

我們會(huì)看到有很多的網(wǎng)站我們點(diǎn)擊圖片就會(huì)進(jìn)入當(dāng)前文件連接了,下面我來給使用wordpress博客的同學(xué)也來介紹此種方法,圖片自動(dòng)鏈接到文章,添加標(biāo)題和ALT屬性.

直接將下面的代碼添加到主題的 functions.php 文件即可:

復(fù)制代碼
代碼如下:
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);

最終的輸出結(jié)果如下:

復(fù)制代碼
代碼如下:
<a href="wordpress-view-history.html" title="WordPress 添加文章瀏覽歷史功能" >
<img src="201303521.png" alt="WordPress 添加文章瀏覽歷史功能" />
</a>

關(guān)鍵詞自動(dòng)添加鏈接

還可以再添加一個(gè)功能,將文章標(biāo)簽作為關(guān)鍵詞,將文章內(nèi)的關(guān)鍵詞自動(dòng)加上鏈接,有利于SEO,別人復(fù)制的時(shí)候,就會(huì)留下鏈接了,在上面的函數(shù)里繼續(xù)添加一段代碼即可:

復(fù)制代碼
代碼如下:
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個(gè)重復(fù)的詞,避免過度SEO
}
}
return $content;
}
add_filter ('the_content', 'auto_post_link',0);

希望本文所述對大家的WordPress建站有所幫助。

上一篇:WordPress快速添加友情鏈接功能的方法

欄    目:WordPress

下一篇:WordPress自動(dòng)給文章添加nofollow屬性的實(shí)現(xiàn)方法

本文標(biāo)題:WordPress給文章圖片自動(dòng)添加鏈接的方法

本文地址:http://www.jygsgssxh.com/a1/WordPress/12683.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有