WordPress WooCommerce 在每个产品按钮上显示产品类别
WordPress WooCommerce display product category on every product button
在 Woocommerce 中,每个产品按钮默认为产品图片、产品名称、价格和添加到购物车按钮。但是,我想在每个产品按钮中添加该产品属于哪个类别(这会将用户引导至类别页面)。
我该怎么做?
这是我想要实现的示例:
这可以使用挂接到 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+
在 Woocommerce 中,每个产品按钮默认为产品图片、产品名称、价格和添加到购物车按钮。但是,我想在每个产品按钮中添加该产品属于哪个类别(这会将用户引导至类别页面)。
我该怎么做?
这是我想要实现的示例:
这可以使用挂接到 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+