问题
I'm trying to Show subcategories (not subsubcategories,etc) under current category in Woocommerce like this Web: http://www.qs-adhesivos.es/app/productos/productos.asp?idioma=en
For Example, Construction is the category, and Sealants & adhesives, waterproofing, plyurethane foams… are subcategories.
Sealants & Mastics is the category, and ACETIC SILICONE SEALANT, NEUTRAL SILICONE SEALANT, ACRYLIC SEALANT… are subcategories…
Already have an archive-product.php in a woocommerce folder under my child theme.
Already tried some code and it applies but it's not what I want.
回答1:
The following code will display the formatted linked product subcategories from current product category for product category archive pages:
if ( is_product_category() ) {
$term_id = get_queried_object_id();
$taxonomy = 'product_cat';
// Get subcategories of the current category
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => true,
'parent' => get_queried_object_id()
]);
$output = '<ul class="subcategories-list">';
// Loop through product subcategories WP_Term Objects
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $taxonomy );
$output .= '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';
}
echo $output . '</ul>';
}
Tested and works.
USAGE EXAMPLES:
1) You can use this code directly in archive-product.php
template file.
2) You can embed the code in a function, replacing the last line echo $output . '</ul>';
by return $output . '</ul>';
, as for shortcodes, the display is always returned.
3) You can embed the code using action hooks like woocommerce_archive_description
:
// Displaying the subcategories after category title
add_action('woocommerce_archive_description', 'display_subcategories_list', 5 );
function display_subcategories_list() {
if ( is_product_category() ) {
$term_id = get_queried_object_id();
$taxonomy = 'product_cat';
// Get subcategories of the current category
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => true,
'parent' => $term_id
]);
echo '<ul class="subcategories-list">';
// Loop through product subcategories WP_Term Objects
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $taxonomy );
echo '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';
}
echo '</ul>';
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
To display it after the category description, change the hook priority from 5
to 20
in:
add_action('woocommerce_archive_description', 'display_subcategories_list', 5 );
like:
add_action('woocommerce_archive_description', 'display_subcategories_list', 20 );
来源:https://stackoverflow.com/questions/57767843/get-the-subcategories-of-the-current-product-category-in-woocommerce-archives