Nik7
Nik7

Reputation: 386

Disallow backorders product option globally (in admin too) on WooCommerce

I have a question about how to disable backorders in WooCommerce globally. I found this here:

How to disable globally backorders in WooCommerce

https://wordpress.stackexchange.com/questions/334083/woocommerce-is-it-possible-to-overide-the-settings-for-allowing-to-purchase-out

I use now add_filter( 'woocommerce_product_backorders_allowed', '__return_false' );. But is is still possible to set that option to allowed. So my question is, if I set a product to "Backorder allowed" and this snipped is active. After save the product "Backorder allowed" is visible. But is that only a display thing and in the back Backorder are not possible even if "allowed" is selected?

It would be nice, if there is no way to change that setting. Maybe gray-out that option in the edit product overview?

Is something possible?

Cheers

Upvotes: 2

Views: 893

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254388

You can use the following to disable backorder settings on admin product single pages (that handle product variations too):

add_action( 'admin_footer', 'disable_backorder_option_from_product_settings' );
function disable_backorder_option_from_product_settings() {
    global $pagenow, $post_type;

    if( in_array( $pagenow,  array('post-new.php', 'post.php') ) && $post_type === 'product' ) :
    ?>
    <script>
    jQuery(function($){
        // For product variations
        $('#variable_product_options').on('change', function(){
            $('select[name^=variable_backorders]').each( function(){
                $(this).prop('disabled','disabled').val('no');
            });
        });
        // For all other product types
        $('select#_backorders').prop('disabled','disabled').val('no');
    });
    </script>
    <?php
    endif;
}

For frontend, you will use additionally (if there are still some older products with backorder option enabled):

add_filter( 'woocommerce_product_backorders_allowed', '__return_false', 1000 );
add_filter( 'woocommerce_product_backorders_require_notification', '__return_false', 1000 );

add_filter( 'woocommerce_product_get_backorders', 'get_backorders_return_no' );
add_filter( 'woocommerce_product_variation_get_backorders', 'get_backorders_return_no' );
function get_backorders_return_no( $backorders ){
    return 'no';
}

add_filter( 'woocommerce_product_get_stock_status', 'filter_product_stock_status', 10, 2 );
add_filter( 'woocommerce_product_variation_get_stock_status', 'filter_product_stock_status', 10, 2 );
function filter_product_stock_status( $stock_status, $product ){
    return $product->get_manage_stock() && $product->get_stock_quantity() <= 0 ? 'outofstock' : $stock_status;
}

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

Upvotes: 2

Related Questions