函数
$change_term = wp_set_post_terms( $post_id, $catID, $taxonomy, $boolean );
if ( is_wp_error( $change_term ) ) {
// 这里是添加失败
} else {
// 这里是添加成功
}
描述
该WordPress函数可 修改、清空、替换文章分类。
参数
$post_id,文章的ID,循环中可以使用get_the_ID()函数获取。
$catID,需要添加的分类ID数组,或是字符串或者是单个ID;为Null时,表示清空文章当前分类法下面的分类。
$taxonomy,需要操作的分类法。
$boolean,布尔值,默认为false。false为替换当前分类$catID,true为追加分类$catID。
返回值
boolean
实例
一个修改日主题的例子,意思是:为除了分类ID为12和36的其他所有分类的文章追加ID为843的分类。
$the_query = new WP_Query( array(
'post_type' => 'post',
// 'cat' => 12,
'posts_per_page' => -1,
'category__not_in' => array( 12, 36 )
) );
//$num = 0;
if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
$post = $the_query->post;
$wppay_type = get_post_meta( $post->ID, 'wppay_type', true );
if ( $wppay_type == 3 ) {
$change_term = wp_set_post_terms( $post->ID, 843, 'category', true );
if ( is_wp_error( $change_term ) ) {
// 这里是添加失败
} else {
// 这里是添加成功
}
echo $post->post_title.',
';
}
endwhile; endif; wp_reset_postdata();