问题
I am using the following code to change the wording on a Woo product add to cart button based on its parent category.
The code works but has the following bug. If one of the parent categories is empty (i.e. does not have any sub cats) then the code no longer works.
So the current code must be missing a string to check if parent category is empty or not but I do not know how to code that.
This is the snippet I am running:
// 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;
}
来源:https://stackoverflow.com/questions/50869770/change-add-to-cart-button-text-based-on-woocommerce-parent-product-categories