纯代码实现WordPress 自动为文章添加已使用过的标签

// WordPress 自动为文章添加已使用过的标签
function array2object($array) { // 数组转对象
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){
$obj->$key = $val;
}
}
else {
$obj = $array;
}
return $obj;
}

function object2array($object) { // 对象转数组
if (is_object($object)) {
foreach ($object as $key => $value) {
$array[$key] = $value;
}
}
else {
$array = $object;
}
return $array;
}

function auto_add_tags(){
$post_id = get_the_ID();

if($post_id):
$post_content = get_post($post_id)->post_content;
if(!empty($post_content)){
$tags = get_tags( array('hide_empty' => false) );
if ($tags) {
$i = 0;
$arrs = object2array($tags);shuffle($arrs);$tags = array2object($arrs);// 打乱顺序
foreach ( $tags as $tag ) {
// 如果文章内容出现了已使用过的标签,自动添加这些标签
if ( strpos($post_content, $tag->name) !== false){
if ($i == 6) break; // 控制输出数量
wp_set_post_tags( $post_id, $tag->name, true );
$i++;
}
} //end foreach
}
}
endif;
}
add_action('save_post', 'auto_add_tags'); //添加save_post钩子

/* 自动为文章内的标签添加内链 / 
$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 = ""; $limit = rand($match_num_from,$match_num_to); $content = preg_replace( '|(]+>)(.)('.$ex_word.')(.)(]>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$content = preg_replace( '|(?)('.$ex_word.')(.?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.?)|(?)))('. $cleankeyword . ')(?!(([^<>]?)>)|([^>]?))\'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);

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。[本站由 WEEX唯客交易所(官网www.weex.com)提供赞助]