WordPress implements automatic article tag extraction and link addition

WordPress implements automatic article tag extraction and link addition


There are many ways to automatically extract tags from articles in WordPress, and the most convenient way is to use a plug-in. Today I will share a method to automatically extract tags and add links to articles without using plugins.
Log in to the blog backend, open the function.php function of the blog theme, and add the following code to this file:

//連接數量
$match_num_from = 1; //一個關鍵字少于多少不替換
$match_num_to = 10; //一個關鍵字最多替換
//連接到WordPress的模塊
add_filter('the_content','tag_link',1);
//按長度排序
function tag_sort($a, $b){
if ( $a->name == $b->name ) return 0;
return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
//改變標簽關鍵字
function tag_link($content){
global $match_num_from,$match_num_to;
$posttags = get_the_tags();
if ($posttags) {
usort($posttags, "tag_sort");
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
//連接代碼
$cleankeyword = stripslashes($keyword);
$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('View all posts in %s'))."\"";
$url .= ' target="_blank"';
$url .= ">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from,$match_num_to);
//不連接的代碼
$content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
}
}
return $content;
}

Purely for your own convenience.

<<:  $19.95/month/512M memory/24G space/2TB traffic/XEN VPS —— Linode

>>:  VPS for less than $20 per year

Recommend

QYun-SoarTeam 2GB RAM KVM VPS Los Angeles Simple Review

Details: QYun-SoarTeam: 20.5 yuan/month/600MB mem...

BackupTank: $10/month/1GB memory/1TB space/2TB traffic/1Gbps port/KVM/German He

BackupTank, a foreign merchant, mainly provides s...

【Double 11】Xura Cloud: Double 11 discount

Shura Cloud is welcoming the most favorable event...

50% off on Godaddy web hosting

Godaddy's 50% discount is pretty good. Detail...

ByteChef: $40/year/U2250/2GB memory/160GB space/unlimited traffic/1 IP/France

ByteChef, an Indian hosting company, now has a sp...

Internoc24: €8.33/month/2GB RAM/120GB HDD/4TB bandwidth/Romania

Internoc24, a veteran hosting provider, has 8 yea...

Java Photo Station Beauty Installation Tutorial

Very good picture site source code, you can use i...