下面的代码可能在循环之外有所帮助。我正在使用它save_post
行动挂钩。
// get the assigned terms to the post
$terms = get_the_terms( $post_id, \'category\' );
// create an empty array for storing category names
$terms_meta = [];
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
$terms_meta[] = $term->name;
}
}
if ( ! empty( $terms_meta ) ) {
$terms_string = implode( \', \', $terms_meta );
} else {
$terms_string = \'\';
}
print_r( $terms_string );