我有一个Woocommerce商店与父类别和子类别 .
例如,父类别是Menswear,其两个子类别是衬衫和裤子 .
我想更改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;
}
只是为了澄清:
我希望的是一个解决方案,使用数组中的父类别(Menswear),而不是子类别衬衫和裤子 . 在我的网站中,我只有四个父类别,但每个类别都有几十个子类别 . 我正在寻找一种解决方案,避免必须列出数组中的几十个子类,并且只使用四个父类别 . 是否可以根据父类别更改添加到购物车文本? (即,属于该父项的子类别中的所有产品都将发生更改) .
进一步澄清:
假设我有四个父类别:红色,黄色,绿色和蓝色 .
这些父类别中的每一个都有多个子类别,如下所示:
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 .
我希望黄色子猫1和黄色子猫2中的产品具有添加到购物车文本购买黄色 .
我希望Green subcat 1和Green subcat 2中的产品具有添加到购物车文本BUY GREEN .
我希望Blue subcat 1和Blue subcat 2中的产品具有添加到购物车文本BUY BLUE .
在我的实际网站中,每个父类别都有超过50个子类别,因此将这些列为数组是不切实际的 .
感谢为什么我正在寻找一个解决方案,根据父类别更改添加到购物车文本 .
UPDATE
基于@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;
}
FURTHER UPDATE: 此解决方案有一个错误 . 如果其中一个父类别为空,则代码不起作用 .
看这里:
Bug in Change Add To Cart button text based on parent product categories in Woo
2 回答
Updated
首先,您将在下面找到一个实用程序函数,以从父产品类别中获取子数组 . 然后你就可以在你的钩子函数中使用它了 .
您可以使用不同的文本按钮处理多个父产品类别 .
代码:
代码位于活动子主题(或活动主题)的function.php文件中 . 经过测试和工作 .
感谢@LoicTheAztec的投入 .
在编辑了他的代码后,我想出了这个 .
经过测试和工作 .