Change Add To Cart button text based on Woocommerce parent product categories

拜拜、爱过 提交于 2019-12-08 04:21:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!