Home > Enterprise >  Issue when using "woocommerce_product_add_to_cart_text" filter hook
Issue when using "woocommerce_product_add_to_cart_text" filter hook

Time:09-16

I wrote a function to change Add To Cart button text for products on backorder.

woocommerce_product_single_add_to_cart_text works fine, but using woocommerce_product_add_to_cart_text crashes the page.

In the error log I see that it freezes class-wp-term.php.

Here's my function code:

function change_button_text_on_backorder() {

    if (! is_admin()) {
        global $product;
        
        $qty = $product->get_stock_quantity();
        $button_text = $product->add_to_cart_text();

        if  ( $qty < 1 && $product->backorders_allowed() ) { // backorders allowed?
            $button_text = 'BACKORDER';
        }
        return $button_text;
    }
}

add_filter('woocommerce_product_single_add_to_cart_text', 'change_button_text_on_backorder');
add_filter('woocommerce_product_add_to_cart_text', 'change_button_text_on_backorder');

I'm using WordPress 5.8, WooCommerce 5.6. Any suggestions why it crashes?

CodePudding user response:

Your code contains some mistakes

  • $product is passed as an argument, so there is no need to use a global variable
  • $product->add_to_cart_text() is also not necessary, as this is also passed as an argument

So you get:

function filter_woocommerce_product_add_to_cart_text( $add_to_cart_text, $product ) {
    // Get stock quantity
    $qty = $product->get_stock_quantity();

    // Backorders allowed?
    if  ( $qty < 1 && $product->backorders_allowed() ) {
        $add_to_cart_text = __( 'Backorder', 'woocommerce' );
    }

    return $add_to_cart_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'filter_woocommerce_product_add_to_cart_text', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'filter_woocommerce_product_add_to_cart_text', 10, 2 );
  • Related