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

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

代码一:

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;
			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', '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 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', 'auto_add_tags' );

发表回复

后才能评论