猿问

获取 Woocommerce 档案中当前产品类别的子类别

我正在尝试在 Woocommerce 中显示当前类别下的子类别(不是子类别等),比如这个网站:http ://www.qs-adhesivos.es/app/productos/productos.asp?idioma=en

例如,建筑是类别,密封剂和粘合剂、防水材料、聚氨酯泡沫……是子类别。

密封剂和胶粘剂是类别,而醋酸硅酮密封剂、中性硅酮密封剂、丙烯酸密封剂……是子类别……

在我的子主题下的 woocommerce 文件夹中已经有一个 archive-product.php。

已经尝试了一些代码并且它适用,但这不是我想要的。


狐的传说
浏览 177回答 1
1回答

眼眸繁星

以下代码将显示产品类别存档页面的当前产品类别的格式化链接产品子类别:if ( is_product_category() ) {&nbsp; &nbsp; $term_id&nbsp; = get_queried_object_id();&nbsp; &nbsp; $taxonomy = 'product_cat';&nbsp; &nbsp; // Get subcategories of the current category&nbsp; &nbsp; $terms&nbsp; &nbsp; = get_terms([&nbsp; &nbsp; &nbsp; &nbsp; 'taxonomy'&nbsp; &nbsp; => $taxonomy,&nbsp; &nbsp; &nbsp; &nbsp; 'hide_empty'&nbsp; => true,&nbsp; &nbsp; &nbsp; &nbsp; 'parent'&nbsp; &nbsp; &nbsp; => get_queried_object_id()&nbsp; &nbsp; ]);&nbsp; &nbsp; $output = '<ul class="subcategories-list">';&nbsp; &nbsp; // Loop through product subcategories WP_Term Objects&nbsp; &nbsp; foreach ( $terms as $term ) {&nbsp; &nbsp; &nbsp; &nbsp; $term_link = get_term_link( $term, $taxonomy );&nbsp; &nbsp; &nbsp; &nbsp; $output .= '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';&nbsp; &nbsp; }&nbsp; &nbsp; echo $output . '</ul>';}测试和工作。使用示例:1) 您可以直接在archive-product.php模板文件中使用此代码。2)可以在一个功能嵌入的代码,替换最后一行echo $output . '</ul>';通过return $output . '</ul>';,对于简码,总是返回显示。3)您可以使用以下动作挂钩嵌入代码woocommerce_archive_description:// Displaying the subcategories after category titleadd_action('woocommerce_archive_description', 'display_subcategories_list', 5 );&nbsp;function display_subcategories_list() {&nbsp; &nbsp; if ( is_product_category() ) {&nbsp; &nbsp; &nbsp; &nbsp; $term_id&nbsp; = get_queried_object_id();&nbsp; &nbsp; &nbsp; &nbsp; $taxonomy = 'product_cat';&nbsp; &nbsp; &nbsp; &nbsp; // Get subcategories of the current category&nbsp; &nbsp; &nbsp; &nbsp; $terms&nbsp; &nbsp; = get_terms([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'taxonomy'&nbsp; &nbsp; => $taxonomy,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'hide_empty'&nbsp; => true,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'parent'&nbsp; &nbsp; &nbsp; => $term_id&nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp; echo '<ul class="subcategories-list">';&nbsp; &nbsp; &nbsp; &nbsp; // Loop through product subcategories WP_Term Objects&nbsp; &nbsp; &nbsp; &nbsp; foreach ( $terms as $term ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $term_link = get_term_link( $term, $taxonomy );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; echo '</ul>';&nbsp; &nbsp; }}代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。要将其显示在类别描述之后,请将挂钩优先级从更改5为20in:add_action('woocommerce_archive_description', 'display_subcategories_list', 5 );&nbsp;喜欢:add_action('woocommerce_archive_description', 'display_subcategories_list', 20 );&nbsp;
随时随地看视频慕课网APP
我要回答