【发布时间】:2022-01-20 15:44:36
【问题描述】:
我们的产品类别设置如下:
主要类别 1
-子类别 1.1
-子类别 1.2
-子类别 1.3
主类 2
-子类别 2.1
-子类别 2.2
-子类别 2.3
等等
使用以下代码,我试图在类别页面上的产品名称旁边显示父类别。发生的情况是,产品的类别名称仅在产品放置在父类别和子类别中时才会显示。否则不会显示父类别的名称。例如;如果产品“A”已放置在父类别 1 中,则没有可见的类别名称。如果我还将产品放在子类别 1.3 中,则父类别是可见的。如何解决?
//remove the Default Title and call another function which will show your own title in place
remove_action('woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title',10);
add_action('woocommerce_shop_loop_item_title','fun',10);
function fun()
{
global $product;
// If the WC_product Object is not defined globally
if ( ! is_a( $product, 'WC_Product' ) ) {
$product = wc_get_product( get_the_id() );
}
//get product category
$product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );
if ( $product_cats && ! is_wp_error ( $product_cats ) ){
//$single_cat = array_shift( $product_cats );
?>
<!--<h2 itemprop="name" class="product_category_title"><span class="product_category"><?php //echo $single_cat->name; ?></span> | <?php //echo $product->get_name();?></h2>!-->
<h2 itemprop="name" class="product_category_title"><span class="product_category"><?php echo $product_cats[1]->name; ?></span> | <?php echo $product->get_name();?></h2>
<?php }
}
【问题讨论】:
标签: php wordpress woocommerce categories