我正在Woocommerce中使用Wordpress,我在产品内容产品单的详细页面上。php。
我创建了几个“sub”,只需打印与该产品关联的子类别。
我正在使用此代码:
$categories = array (
\'type\' => \'product\',
\'child_of\' => 1,
\'parent\' => \'8\',
\'orderby\' => \'term_group\',
\'hide_empty\' => true,
\'hierarchical\' = > 1,
\'exclude\' => \'\',
\'property\' => \'\',
\'number\' => \'\',
\'taxonomy\' => \'product_cat\',
\'pad_counts\' => false);
$cats = get_categories ($categories);
foreach ($cats as $cat) {
echo \'<a <br/> href="\'. get_term_link($cat-> slug,\' product_cat \').\' "> \'. $cat-> name.\'</a>\';
}
其中“parent”=>“8”是“我的类别父亲的id”
但此代码打印的所有子类别都不是空的,我只对这些子类别感兴趣,而不是本产品。
谢谢,祝你好运
SO网友:Omar Tariq
根据您的要求配置product\\u id和parent\\u category\\u id。
/* This is product id */
$product_id = 1;
/* This is the id of the parent category */
$parent_category_id = 8;
$cats = get_categories ( array (
\'type\' => \'product\',
\'parent\' => $parent_category_id,
\'orderby\' => \'term_group\',
\'hide_empty\' => true,
\'hierarchical\' = > 1,
\'exclude\' => \'\',
\'property\' => \'\',
\'number\' => \'\',
\'taxonomy\' => \'product_cat\',
\'pad_counts\' => false
));
$non_empty_sub_categories_ids = array_map(create_function(\'$cat\', \'return $cat->term_id;\'), $cats);
$product_cats = get_the_terms( $product_id, \'product_cat\' );
foreach ($product_cats as $product_cat) {
if(in_array($product_cat->term_id, $non_empty_sub_categories_ids)) {
echo \'<a <br/> href="\'. get_term_link($product_cat->slug,\' product_cat \').\' "> \'. $product_cat->name.\'</a>\';
}
}