【问题标题】:WooCommerce - Assign parent term when child term is setWooCommerce - 设置子术语时分配父术语
【发布时间】:2020-04-26 12:17:19
【问题描述】:

我有一个 WooCommerce 设置,当我创建新产品时,我会像往常一样为产品分配一个类别。

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

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

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

注意:我的大部分产品都是其他用户从前端创建的,所以我不能 只需选择其他框,我知道这是一个选项。

我目前的尝试:

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

这仅设置最高父项。

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案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 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-10
      • 2015-01-13
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 2012-03-09
      • 2011-09-10
      • 1970-01-01
      相关资源
      最近更新 更多