【发布时间】:2018-11-12 14:45:47
【问题描述】:
我有一个包含父类别和子类别的 Woocommerce 商店。
例如,父类别是男装,其两个子类别是衬衫和裤子。
我想为 Menswear 父类别中的所有产品更改所有单个产品页面上的“添加到购物车”按钮文本。也就是说,衬衫和裤子子类别中的所有产品。
以下代码实现了这一点,但必须有更好的方法在 if 语句中使用父类别而不是两个子类别。
很遗憾,我不知道该怎么做,有人可以帮忙吗?
add_filter( 'woocommerce_product_single_add_to_cart_text', 'product_cat_single_add_to_cart_button_text', 20, 1 );
function product_cat_single_add_to_cart_button_text( $text ) {
if( has_term( array('shirts','pants'), 'product_cat') )
$text = __( 'Buy Menswear', 'woocommerce' );
return $text;
}
澄清一下:
我所希望的解决方案是使用数组中的父类别(男装)而不是子类别衬衫和裤子。在我的站点中,我只有四个父类别,但每个类别都有几十个子类别。我一直在寻找一种避免在数组中列出几十个子目录的解决方案,而只使用四个父类别。是否可以根据父类别更改添加到购物车的文本? (也就是说,该更改将发生在属于该父级的子类别中的所有产品上)。
进一步说明:
假设我有四个父类别:红色、黄色、绿色和蓝色。
每个父类别都有多个子类别,如下所示:
RED
Red subcat 1
Red subcat 2
YELLOW
Yellow subcat 1
Yellow subcat 2
GREEN
Green subcat 1
Green subcat 2
BLUE
Blue subcat 1
Blue subcat 2
我希望 Red subcat 1 和 Red subcat 2 中的产品具有添加到购物车文本 BUY RED。
我希望 Yellow subcat 1 和 Yellow subcat 2 中的产品具有添加到购物车文本 BUY YELLOW。
我希望 Green subcat 1 和 Green subcat 2 中的产品具有添加到购物车文本 BUY GREEN。
我希望 Blue subcat 1 和 Blue subcat 2 中的产品具有添加到购物车文本 BUY BLUE。
在我的实际网站中,每个父类别都有超过 50 个子类别,因此将它们列为数组是不切实际的。
这就是为什么我要寻找一种解决方案来根据父类别更改添加到购物车文本的原因。
更新
基于@LoicTheAztec 工作代码(谢谢),这是我的最终工作代码:
// Utility function to get the childs array from all parent categories
function get_the_childs( $product_category ){
$taxonomy = 'product_cat';
$parent = get_term_by( 'slug', sanitize_title( $product_category ), $taxonomy );
return get_term_children( $parent->term_id, $taxonomy );
}
// Changing the add to cart button text for product based on parent category
add_filter( 'woocommerce_product_single_add_to_cart_text', 'product_cat_single_add_to_cart_button_text', 20, 1 );
function product_cat_single_add_to_cart_button_text( $text ) {
global $product;
if( has_term( get_the_childs('reds'), 'product_cat', $product->get_id() ) )
$text = __( 'Buy Red', 'woocommerce' );
elseif( has_term( get_the_childs('yellow'), 'product_cat', $product->get_id() ) )
$text = __( 'Buy Yellow', 'woocommerce' );
elseif( has_term( get_the_childs('green'), 'product_cat', $product->get_id() ) )
$text = __( 'Buy Green', 'woocommerce' );
elseif( has_term( get_the_childs('blue'), 'product_cat', $product->get_id() ) )
$text = __( 'Buy Blue', 'woocommerce' );
return $text;
}
进一步更新: 这个解决方案有一个错误。如果父类别之一为空,则代码不起作用。
看这里:
Bug in Change Add To Cart button text based on parent product categories in Woo
【问题讨论】:
标签: php wordpress button woocommerce product