按子类别对WooCommerce产品进行排序

时间:2019-06-25 23:35:58

标签: php wordpress woocommerce

我需要根据商店页面中属于父类别的子类别对woocommerce产品进行排序。例如,我的父类别为Brand,子类别为Brand 1,Brand 2,Brand 3等。

我需要对产品进行排序,以便商店页面上的第一个产品是品牌1,品牌2,品牌3等的产品。

我认为这可能会有所帮助:Order by custom Woocommerce product sorting in a WP_Query

通过使用以下代码,我可以在产品循环中显示每个产品的子类别:

mvn spring-boot:run

现在我要做的是根据这些子类别对产品进行排序。

谢谢!

1 个答案:

答案 0 :(得分:0)

在这里,您可以使用自定义功能轻松利用WooCommerce产品类别的子类别,该功能利用了父产品类别的信息。

function woocommerce_get_product_category_of_subcategories( $category_slug ){
  $terms_html = array();
  $taxonomy = 'product_cat';

  $parent = get_term_by( 'slug', $category_slug, $taxonomy );

  $children_ids = get_term_children( $parent->term_id, $taxonomy );


  foreach($children_ids as $children_id){
        $term = get_term( $children_id, $taxonomy ); 
        $term_link = get_term_link( $term, $taxonomy ); 
        if ( is_wp_error( $term_link ) ) $term_link = '';

        $terms_html[] = '<a href="' . esc_url( $term_link ) . '" rel="tag" class="' . $term->slug . '">' . $term->name . '</a>';
  }
  return '<span class="subcategories-' . $category_slug . '">' . implode( ', ', $terms_html ) . '</span>';
}

在上面的代码片段中,WP_Term对象获取产品类别的父级。接下来,它获取数组中的子ID。最后,通过遍历子ID数组的循环,将子类别显示在HTML中。

有关更多详细信息,请查看https://www.cloudways.com/blog/display-categories-in-woocommerce/

相关问题