我有一个WooCommerce设置,当我创建一个新产品时,我会像往常一样为产品分配一个类别。
Clothing
- Womens
-- Accessories
- Mens
-- Accessories <-- assigned to this term
What I am trying to achieve:当我选择子类别时,我还想将该帖子设置为其上方的每个父类别目录。在这种情况下,看起来像:
Clothing <-- assigned to this term
- Womens
-- Accessories
- Mens <-- assigned to this term
-- Accessories <-- assigned to this term
注意:我的大多数产品都是由其他用户从前端创建的,所以我不能只选择其他框,我知道这是一个选项。
My attempt so far:
function set_product_parent_categories( $post_id ) {
$term_ids = wp_get_post_terms( $post_id, \'product_cat\' );
foreach( $term_ids as $term_id ) {
if( $term_id->parent > 0 ) {
// Assign product to the parent category too.
wp_set_object_terms( $post_id, $term_id->parent, \'product_cat\' );
}
}
}
add_action( \'woocommerce_update_product\', __NAMESPACE__.\'\\\\set_product_parent_categories\', 10, 1 );
这仅设置顶级父项
最合适的回答,由SO网友:wharfdale 整理而成
这将检查是否存在层次结构,并将所有父类别设置为选中状态。此函数假设如果已经设置了多个类别,则不要执行此函数,因为如果设置了多个类别,则类别是正确的。
function set_product_parent_categories( $post_id ) {
$category = wp_get_post_terms( $post_id, \'product_cat\' );
// If multiple categories are set. Bail Out
if (count ($category) > 1 ) return;
$terms = array($category[0]->term_id);
if ($category[0]->parent > 0){
$parent = $category[0]->parent;
while ($parent > 0){
// Make an array of all term ids up to the parent.
$terms[] = $parent;
$grandpa = get_term($parent, \'product_cat\');
$parent = $grandpa->parent;
}
}
// If multiple terms are returned, update the object terms
if (count($terms) > 1) wp_set_object_terms( $post_id, $terms, \'product_cat\' );
}
add_action( \'woocommerce_update_product\', \'set_product_parent_categories\', 10, 1 );