John Davidson

php - WooCommerce products: Allow backorders only for specific user roles

0 comments
Message:


I want to allow backorders for specific customer roles.
Code i writed is:


// BackOrder Allow Part #1
add_filter( 'woocommerce_product_backorders_allowed', 'woocommerce_product_backorders_allowed', 10, 3 );
function woocommerce_product_backorders_allowed( $backorder_allowed, $product_id, $product ){
if ( current_user_can('administrator') ) {
$backorder_allowed = true;
} else {
$backorder_allowed = false;
}

return $backorder_allowed;
}

// BackOrder Allow Part #2
add_filter( 'woocommerce_product_get_stock_status', 'woocommerce_product_get_stock_status', 10, 2 );
function woocommerce_product_get_stock_status( $stock_status, $product ) {
if ( current_user_can('administrator') ) {
return 'onbackorder';
}
else {
return 'outofstock';
}

}

Seems this gived result only for simple product.
How i can make work for other product types.
I need to work for simple, variable and yith-bundle.
Any help will be appreciated!
thanks!



My Answer:
To make this code work for other product types such as variable and yith-bundle, you can modify the code to check the product type before allowing backorders. Here's an updated version of the code:

php
// BackOrder Allow Part #1
add_filter( 'woocommerce_product_backorders_allowed', 'woocommerce_product_backorders_allowed', 10, 3 );
function woocommerce_product_backorders_allowed( $backorder_allowed, $product_id, $product ){
if ( current_user_can('administrator') ) {
$backorder_allowed = true;
} else {
if ( $product->is_type( 'simple' ) || $product->is_type( 'variable' ) || $product->is_type( 'yith_bundle' ) ) {
$backorder_allowed = false;
}
}

return $backorder_allowed;
}

// BackOrder Allow Part #2
add_filter( 'woocommerce_product_get_stock_status', 'woocommerce_product_get_stock_status', 10, 2 );
function woocommerce_product_get_stock_status( $stock_status, $product ) {
if ( current_user_can('administrator') ) {
return 'onbackorder';
} else {
if ( $product->is_type( 'simple' ) || $product->is_type( 'variable' ) || $product->is_type( 'yith_bundle' ) ) {
return 'outofstock';
}
}

}


This code will now check the product type before allowing backorders for the specific customer roles. Make sure to replace 'yith_bundle' with the correct product type if it's different in your WooCommerce setup.

Rate this post

5 of 5 based on 9321 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us