那么有沒有可能讓WordPress站點自動為文章添加以前使用過的Tag標簽呢?有沒有可能讓WordPress站點自動為文章的Tag標簽添加鏈接變成內鏈呢?這兩個問題的答案都是肯定的,今天就跟大家分享WordPress站點實現自動為文章添加Tag標簽,并自動為這些標簽添加鏈接變成內連接。
WordPress純代碼實現自動添加文章標簽的實現方法:只需要將以下代碼添加到主題的functions.php文件最后一個?>即可
/* 自動為文章添加標簽 */
add_action(‘save_post’, ‘auto_add_tags’);
function auto_add_tags(){
$tags = get_tags( array(‘hide_empty’ => false) );
$post_id = get_the_ID();
$post_content = get_post($post_id)->post_content;
if ($tags) {
foreach ( $tags as $tag ) {
// 如果文章內容出現了已使用過的標簽,自動添加這些標簽
if ( strpos($post_content, $tag->name) !== false)
wp_set_post_tags( $post_id, $tag->name, true );
}
}
}
以上代碼的功能就是在我們發布/保存/更新文章時,自動檢測文章中的內容,是否出現曾經使用過的標簽。如果出現過就會自動為文章添加這些標簽。如我們站點有標簽:主機評測,那么只要我們的文章內容中出現過主機評測,那么就會自動為該篇文章添加“主機評測”標簽。
WordPress純代碼實現自動為文章內的標簽添加內鏈的方法:同樣是將以下代碼添加到主題的functions.php文件最后一個?>即可
/* 自動為文章內的標簽添加內鏈 */
$match_num_from = 1; //一篇文章中同一個標簽少于幾次不自動鏈接
$match_num_to = 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, ‘$’),__(‘【查看含有[%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;
}
add_filter(‘the_content’,’tag_link’,1);


















