在Woocommerce中,每个产品按钮都默认为产品图片,产品名称,价格和添加到购物车按钮。但是,我想在每个产品按钮中添加产品所属的类别(将用户引导到类别页面)。
我该怎么做?
这是我想要实现的一个例子:
答案 0 :(得分: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 +