自动为WordPress文章添加标签

爱德网 WordPress经验评论132阅读模式

通过下面的代码可自动为WordPress文章添加已使用过的标签。

将代码添加到当前主题函数模板 functions.php 中:

自动为WordPress文章添加标签

自动为WordPress文章添加标签

代码一:

function zm_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;
			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++;
				}
			}
		}
	}
	endif;
}
add_action( 'save_post', 'zm_auto_add_tags' );

代码二,打乱标签排序,每次更新都会变化

function arraytoobject( $array ) {
	if ( is_array( $array ) ) {
		$obj = new StdClass();
		foreach ( $array as $key => $val ) {
			$obj->$key = $val;
		}
	} else {
		$obj = $array;
	}
	return $obj;
}
 
function objecttoarray( $object ) {
	if ( is_object( $object ) ) {
		foreach ( $object as $key => $value ) {
			$array[$key] = $value;
		}
	} else {
		$array = $object;
	}
	return $array;
}
 
function zm_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 = objecttoarray( $tags );
			shuffle( $arrs );
			$tags = arraytoobject( $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++;
				}
			}
		}
	}
	endif;
}
add_action( 'save_post', 'zm_auto_add_tags' );

使用时需要注意的是,当你的网站标签非常多,比如几千个,发表更新文章时可能会卡死。

weinxin
我的微信
微信及版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!其他文章来源于网络,如有侵权,请联系我!
评论  0  访客  0
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定