簡體   English   中英

Woocommerce 在類別頁面的產品名稱旁邊顯示父類別

[英]Woocommerce show parent category next to product name on category page

我們的產品類別設置如下:

主要類別 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 }
}

我相信問題出在這條線上

<h2 itemprop="name" class="product_category_title"><span class="product_category"><?php echo $product_cats[1]->name; ?></span> |  <?php echo $product->get_name();?></h2>

您正在使用數組中的第二項來顯示名稱,當有子類別時,這將是一個數組。 並且數組中的類別不一定按照父子類別的順序。 所以你需要循環遍歷 $product_cats 的結果,並在打印之前確定哪一個是父級

//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 ) ){
        
        foreach ( $product_cats as $product_cat ) {
            if ( $product_cat->parent == 0 ) {
        ?>

                <h2 itemprop="name" class="product_category_title"><span class="product_category"><?php echo $product_cat->name; ?></span> |  <?php echo $product->get_name();?></h2>
        <?php   
                break;
            }
        }
    }
}

這假設您只會將 1 個主要類別分配給產品

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM