2017-08-09 237 views
1

在Woocommerce中,每個產品按鈕默認爲產品圖像,產品名稱,價格和添加到購物車按鈕。但是,我想要在每個產品按鈕中添加產品所屬的類別(這會將用戶引導至類別頁面)。WordPress WooCommerce在每個產品按鈕上顯示產品類別

我怎樣才能做到這一點?

這是什麼,我想實現一個例子:

enter image description here

回答

1

這是可能的使用woocommerce_loop_add_to_cart_link過濾鉤子鉤住這個自定義功能,這樣一來:

// Shop pages: we replace the button add to cart by a link to the main category archive page 
add_filter('woocommerce_loop_add_to_cart_link', 'custom_text_replace_button', 10, 2); 
function custom_text_replace_button($button, $product) { 
    // Get the product categories IDs 
    $category_ids = $product->get_category_ids(); 

    // return normal button if no category is set or if is not a shop page 
    if(empty($category_ids) || ! is_shop()) return $button; 

    // Iterating through each product category 
    foreach($product->get_category_ids() as $category_id){ 
     // The product category WP_Term object 
     $term_obj = get_term_by('id', $category_id, 'product_cat'); 
     // Only for first main category 
     if($term_obj->parent == 0){ 
      break; // we stop the loop 
     } 
    } 

    // The custom button below 
    $button_text = __("Visit", "woocommerce") . ' ' . $term_obj->name; 
    $button_link = get_term_link($term_obj->slug, 'product_cat'); 
    return '<a class="button" href="' . $button_link . '">' . $button_text .'</a>'; 
} 

代碼進入你活動的兒童主題(或主題)的function.php文件或者任何插件文件中。

該代碼測試和工程上woocommerce版本3+

+1

謝謝你,這可以幫助像我這樣的很多的新手:) – Squish

+0

側面說明:這並不對所有類型的主題的工作,他們中的一些需要多一點調整:) – Squish

+0

@SnowBut。如果你願意,你可以添加一個編輯到這個答案(最後),我會接受它......很難讓所有的定製主題適用於所有的配置,設置和特殊情況有效的工作。謝謝 – LoicTheAztec

相關問題