要将结果限制为当前产品类别的子级,可以使用parent
中的参数get_terms(). 这个id
当前类别的,设置为parent
值,将使用get_queried_object().
$term_id = 0;
$queried_object = get_queried_object();
//
// check if it\'s a custom category
if ( $queried_object instanceof WP_Term )
$term_id = $queried_object->term_id;
$args = array(
\'taxonomy\' => \'product_cat\',
\'parent\' => $term_id, // get only direct children
//\'child_of\' => $term_id, // get all children
//\'hide_empty\' => false,
);
$terms = get_terms( $args );
如果要将当前类别附加到结果(在子类别之前):
$terms = get_terms( $args );
if ($queried_object instanceof WP_Term) {
array_unshift( $terms, $queried_object );
}
完整代码示例:
if ( is_archive(\'product\') ) // OR: is_product_category()
{
$term_id = 0;
$queried_object = get_queried_object();
//
// check if it\'s a custom category
if ( $queried_object instanceof WP_Term )
$term_id = $queried_object->term_id;
$args = array(
\'taxonomy\' => \'product_cat\',
\'parent\' => $term_id, // get only direct children
//\'child_of\' => $term_id, // get all children
//\'hide_empty\' => false,
);
$terms = get_terms( $args );
//
// add current category at beginning
if ($queried_object instanceof WP_Term) {
array_unshift( $terms, $queried_object );
}
//
// Check if any term exists and print them all
if ( ! empty( $terms ) && is_array( $terms ) )
{
echo \'<ul>\';
foreach ( $terms as $term ) {
printf(\'<li><a href="%s">%s</a></li>\',
esc_url( get_term_link( $term ) ),
$term->name
);
}
echo \'</ul>\';
}
}