WordPress写文章时自动添加标签及自动内链关键字
首先是插件版:WP AutoTags,Simple Tags,WP Tag Seeder
每当我们使用 wordpress 发布文章的时候,文章页面的底部都会有添加标签(tags),这样既能给访问者明确这篇文章的重点,也能够给网站的 SEO 带来很多好处。但是都需要手动给 WordPress 文章添加标签,这样每次都需要手动的添加耗费精力及时间,那么我们就有没有可能实现自动为新文章添加标签的功能呢?
通过给 WordPress 主题添加代码的方式实现这个功能。代码非常简单那如果你一看明白其中的原理。首先来到你的 function.php 文件,打开 WordPress 后台>>外观>>编辑>>模板函数 function.php ,将以下代码粘贴到 function.php 中:
// 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;
}
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) {
$i = 0;
$arrs = object2array($tags);shuffle($arrs);$tags = array2object($arrs);// 打乱顺序
foreach ( $tags as $tag ) {
// 如果文章内容出现了已使用过的标签,自动添加这些标签
if ( strpos($post_content, $tag->name) !== false){
if ($i == 5) { // 控制输出数量
break;
}
wp_set_post_tags( $post_id, $tag->name, true );
$i++;
}
}
}
}
以上就是纯代码方式自动为 WordPress 新文章添加标签的全部内容,如果您有更好的方法,不妨联系我们一起交流。
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 = "".addcslashes($cleankeyword, '$')."";
$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 . ')(?!(([^<>]*?)>)|([^>]*?))\'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);
/* 自动为文章内的标签添加内链结束 *
代码中注释的很清楚,可以自行改正。
二、指定关键词自动内链
将以下代码添加到当前主题的functions.php文件中保存:
/* 文章指定关键词添加内链开始 */
function replace_text_wps($text){
$replace = array(
'商娱网' => '商娱网',
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
add_filter('the_content', 'replace_text_wps');
大家自行把代码中的关键词与链接换成自己的,需要其他关键词复制那一行代码即可,非常方便,这个方法有个缺陷就是不能控制关键词锚文本次数,只要在文章中出现的关键词不管几次都会加上链接
共有 0 条评论