Last active
June 26, 2024 08:22
-
-
Save braddalton/9af75197312b2a4cd838507eed68e3bc to your computer and use it in GitHub Desktop.
Restrict users to backorder specific products
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action('init', 'add_backorder_allowed_role'); | |
function add_backorder_allowed_role() { | |
add_role( | |
'backorder_allowed', | |
__('Backorder Allowed', 'textdomain'), | |
array( | |
'read' => true, // This allows the user to read the content | |
// Add other capabilities as needed | |
) | |
); | |
} | |
add_filter('woocommerce_product_is_in_stock', 'custom_backorder_permission', 10, 2); | |
function custom_backorder_permission($is_in_stock, $product) { | |
// Define the product IDs that allow backorder | |
$allowed_product_ids = array(123, 456, 789); // Replace with your product IDs | |
if (in_array($product->get_id(), $allowed_product_ids) && $product->is_on_backorder(1)) { | |
$current_user = wp_get_current_user(); | |
if (in_array('backorder_allowed', $current_user->roles)) { | |
return true; // Allow backorder for users with the backorder_allowed role | |
} else { | |
return false; // Prevent backorder for all other users | |
} | |
} | |
return $is_in_stock; | |
} | |
add_filter('woocommerce_variation_is_in_stock', 'custom_backorder_permission_for_variations', 10, 2); | |
function custom_backorder_permission_for_variations($is_in_stock, $variation) { | |
// Define the product IDs that allow backorder | |
$allowed_product_ids = array(123, 456, 789); // Replace with your product IDs | |
if (in_array($variation->get_id(), $allowed_product_ids) && $variation->is_on_backorder(1)) { | |
$current_user = wp_get_current_user(); | |
if (in_array('backorder_allowed', $current_user->roles)) { | |
return true; // Allow backorder for users with the backorder_allowed role | |
} else { | |
return false; // Prevent backorder for all other users | |
} | |
} | |
return $is_in_stock; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment