Rename Add to Cart buttons for Out Of Stock Products in WooCommerce 3

纵然是瞬间 提交于 2019-12-31 03:45:07

问题


I would like to rename 'Add to Cart' to 'Sold Out' when product is sold out in WooCommerce.

This is my code:

add_filter( 'add_to_cart_text', 'woo_custom_single_add_to_cart_text' );
add_filter( 'woocommerce_product_single_add_to_cart_text', 
'woo_custom_single_add_to_cart_text' );  // 2.1 +

function woo_custom_single_add_to_cart_text() {

if( $product->get_stock_quantity() == 0 )
    return __( 'Sold Out', 'woocommerce' );
} else {
    return __( 'Add to cart ', 'woocommerce' );
}

But it's not working.

What I am doing wrong please?


回答1:


UPDATE (Working now with variable products and variations)

There is some errors in your code:

1.You need to to set the hooks arguments in your function as $button_text and $product. 2.The add_to_cart_text is deprecated and replaced by woocommerce_product_add_to_cart_text.

In this updated code I have added a jQuery script that catch the selected variation for variable products only (on single product pages) and to change the button text. Now this is working for all cases.

add_filter( 'woocommerce_product_add_to_cart_text', 'customizing_add_to_cart_button_text', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'customizing_add_to_cart_button_text', 10, 2 );
function customizing_add_to_cart_button_text( $button_text, $product ) {

    $sold_out = __( "Sold Out", "woocommerce" );

    $availability = $product->get_availability();
    $stock_status = $availability['class'];

    // Only for variable products on single product pages
    if ( $product->is_type('variable') && is_product() )
    {
    ?>
    <script>
    jQuery(document).ready(function($) {
        $('select').blur( function(){
            if( '' != $('input.variation_id').val() && $('p.stock').hasClass('out-of-stock') )
                $('button.single_add_to_cart_button').html('<?php echo $sold_out; ?>');
            else 
                $('button.single_add_to_cart_button').html('<?php echo $button_text; ?>');

            console.log($('input.variation_id').val());
        });
    });
    </script>
    <?php
    }
    // For all other cases (not a variable product on single product pages)
    elseif ( ! $product->is_type('variable') && ! is_product() ) 
    {
        if($stock_status == 'out-of-stock')
            $button_text = $sold_out.' ('.$stock_status.')';
        else
            $button_text.=' ('.$stock_status.')';
    }
    return $button_text;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works




回答2:


It looks like you forgot to declare $product as a global.

Your filter function should start with global $product;



来源:https://stackoverflow.com/questions/45823061/rename-add-to-cart-buttons-for-out-of-stock-products-in-woocommerce-3

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