我正在尝试获取或列出WooCommerce中当前产品的所有类别名称或ID。
使用此代码:我获得了到类别的完整链接,但我需要它们的名称或ID。
<?php
// Get list of ALL categories for current product
$cats = wc_get_product_category_list( $id );
var_dump($cats);
?>
我想要类别的名称或 ID ,以便可以使用它们进行迭代。
答案 0 :(得分:2)
在主题的functions.php
文件中添加以下代码。
add_action( 'init', function() {
$categories = wp_get_post_terms( 17, 'product_cat' );
if ( ! empty( $categories ) ) {
$html = '<ul>';
foreach( $categories as $category ) {
$html .= "<li>{$category->name}</li>";
}
$html .= '</ul>';
}
echo $html;
die;
});
参考:https://developer.wordpress.org/reference/functions/wp_get_post_terms/
答案 1 :(得分:1)
// Get list of ALL categories for current product
$term_ids = array();
$terms = get_the_terms( 158, "product_cat" );
if(!is_wp_error( $terms )){
foreach ( $terms as $term ) {
$term_ids[] = $term->term_id;
}
}
var_dump($term_ids);exit;
尝试一下