Change product stock availability texts in Woocommerce

拟墨画扇 提交于 2019-12-24 11:46:04

问题


I am trying to change the in stock text next to the quantity available in woocommerce. I am using the stock management in product variations.

I tried this code below:

// change stock text
add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
function wcs_custom_get_availability( $availability, $variation ) {

    // Change In Stock Text
    if (  $variation->is_in_stock() ) {
        $availability['availability'] = __('Available!', 'woocommerce');
    }

    // Change Out of Stock Text
    if ( ! $variation->is_in_stock() ) {
        echo '-------------------------';
        echo __('Sold Out', 'woocommerce');
        $availability['availability'] = __('Sold Out', 'woocommerce');
    }

    return $availability;
}

The code above changes the text but it does not pull in the stock quantity number from the variation stock manager.

Any help is appreciated.


回答1:


The following code will handle all cases including the stock amount display with your custom texts:

add_filter( 'woocommerce_get_availability_text', 'customizing_stock_availability_text', 1, 2);
function customizing_stock_availability_text( $availability, $product ) {
    if ( ! $product->is_in_stock() ) {
        $availability = __( 'Sold Out', 'woocommerce' );
    }
    elseif ( $product->managing_stock() && $product->is_on_backorder( 1 ) )
    {
        $availability = $product->backorders_require_notification() ? __( 'Available on backorder', 'woocommerce' ) : '';
    }
    elseif ( $product->managing_stock() )
    {
        $availability = __( 'Available!', 'woocommerce' );
        $stock_amount = $product->get_stock_quantity();

        switch ( get_option( 'woocommerce_stock_format' ) ) {
            case 'low_amount' :
                if ( $stock_amount <= get_option( 'woocommerce_notify_low_stock_amount' ) ) {
                    /* translators: %s: stock amount */
                    $availability = sprintf( __( 'Only %s Available!', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
                }
            break;
            case '' :
                /* translators: %s: stock amount */
                $availability = sprintf( __( '%s Available!', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
            break;
        }

        if ( $product->backorders_allowed() && $product->backorders_require_notification() ) {
            $availability .= ' ' . __( '(can be backordered)', 'woocommerce' );
        }
    }
    else
    {
        $availability = '';
    }

    return $availability;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.



来源:https://stackoverflow.com/questions/52973710/change-product-stock-availability-texts-in-woocommerce

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