WooCommerce-设置子术语时分配父术语

时间:2020-04-26 12:17:19

标签: wordpress woocommerce

我有一个WooCommerce设置,当我创建新产品时,我将产品分配为常规类别。

Clothing
- Womens
-- Accessories
- Mens
-- Accessories <-- assigned to this term

enter image description here

我要实现的目标:
当我选择一个子类别时,我也想将该帖子设置为它上面每个父类别的直角。在这种情况下,它看起来像:

Clothing <-- assigned to this term
- Womens
-- Accessories
- Mens <-- assigned to this term
-- Accessories <-- assigned to this term

enter image description here

注意:我的大多数产品都是由其他用户从前端创建的,因此我不能 只需选择其他框,我知道这是一个选择。

我到目前为止的尝试:

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 );

这仅设置顶级父项。
enter image description here

1 个答案:

答案 0 :(得分:1)

这将检查是否存在层次结构,并将所有父类别设置为选中状态。此功能假定已经设置了多个类别,则不要执行此功能,因为如果设置了多个类别,则类别将是正确的。

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 );
相关问题