wp_set_post_terms()
使用wp_set_object_terms()
. 有一个叫做set_object_terms
成功设置对象的条件时激发。动作钩看起来像这样
do_action ( \'set_object_terms\', int $object_id, array $terms, array $tt_ids, string $taxonomy, bool $append, array $old_tt_ids )
这里我们可以做的是,在动作回调函数中,我们可以检查插入的术语是否为顶级,如果不是,我们可以从术语对象中获取父ID,然后将父术语添加到post对象中
您可以尝试以下操作:
add_action( \'set_object_terms\', function ( $object_id, $terms, $tt_ids, $taxonomy )
{
// Lets make sure we run this only once
remove_action( current_action(), __FUNCTION__ );
// Lets only target the category taxonomy, if not, lets bail
if ( \'category\' !== $taxonomy )
return;
// Make sure we have terms to avoid bugs
if ( !$tt_ids )
return;
// Get all the terms already assinged to the post-
$post_terms = get_the_terms( $object_id, $taxonomy );
if ( $post_terms ) {
$post_term_ids = wp_list_pluck( $post_terms, \'term_id\' );
// Bail if $post_term_ids === $tt_ids
if ( $post_term_ids === $tt_ids )
return;
}
// We are busy with the category taxonomy, continue to execute
$parent_ids = [];
// Lets loop through the terms and get their parents
foreach ( $tt_ids as $term ) {
// Get the term object
$term_object = get_term_by( \'id\', $term, $taxonomy );
// If top level term, just continue to the next one
if ( 0 === $term_object->parent )
continue;
// Our term is not top level, save the parent term in an array
$parent_ids[] = $term_object->parent;
}
// Make sure we have parent terms, if not, bail
if ( !$parent_ids )
return;
// Make sure we do not have duplicate parent term ID\'s, if so, remove duplicates
$parent_ids = array_unique( $parent_ids );
// Make sure that our parent id\'s not in the $terms array, if so, remove them
$parent_ids = array_diff( $parent_ids, $tt_ids );
// Make sure we still have parent ID\'s left
if ( !$parent_ids )
return;
// Lets add our parent terms to the object\'s other terms
wp_set_object_terms( $object_id, $parent_ids, $taxonomy, true );
}, 10, 4 );
编辑-用例
functions.php
如果我们将任何子条款传递给,则会自动将父条款添加到帖子中
wp_set_object_terms()
.
现在,在模板中,可以执行以下操作
$child_cat_ids = [120]; // Array of child categories
wp_set_object_terms(
147, // Post ID
$child_cat_ids, // Array of child category ID\'s
\'category\', // Taxonomy the terms belongs to
true // Only append terms to existing ones
);
请注意,您只需担心要添加到帖子中的子类别。正如我所说,上面的操作将注意在帖子中添加正确的父项