在设置子类别时将帖子类别设置为包括父级

时间:2020-04-26 作者:wharfdale

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

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

enter image description here

What I am trying to achieve:
当我选择子类别时,我还想将该帖子设置为其上方的每个父类别目录。在这种情况下,看起来像:

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

enter image description here

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

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 );
这仅设置顶级父项
enter image description here

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

相关推荐

Get post categories

我想根据帖子类别做一个过滤器。我试图在数据类别属性中添加类别名称,但似乎不起作用。这就是我所尝试的:<article id=\"post-<?php the_ID(); ?>\" <?php post_class(); ?> data-category=\"<?php $category_detail=get_the_category(); foreach($category_detail as $cd){ $cd->cat_name;}?>\">&#