2017-08-09 238 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

相关问题