Hello,
our store sells variable products:
Single (1pc)
Box Quantity (10pcs)
I want Admins and Reseller roles to go onto a product and have the dropdown variable option preselected to a value (10pcs)
But then non signed in users see the 1pc preselected.
Ive defaulted the form to select 1pc on product backend
However using code i cant seem to get the Reseller/Admin side to work.
// Function to set default quantity attribute based on user role
function set_default_quantity_attribute($default_attributes, $product) {
// Get the user’s role
$user_role = get_user_role();
// Define the list of attributes you want to check for
$attributes_to_check = array(
‘Box (1000pcs)’,
‘Box (500pcs)’,
‘Box (250pcs)’,
‘Box Quantity (4pcs)’,
‘Box Quantity (5pcs)’,
‘Box Quantity (10pcs)’,
);
// Check if the user is a reseller or administrator
if ($user_role === ‘reseller’ || $user_role === ‘administrator’) {
foreach ($attributes_to_check as $attribute_name) {
if ($product->has_attribute($attribute_name)) {
$default_attributes[‘quantity’] = $attribute_name;
break; // Set the first matching attribute and break out of the loop
}
}
}
return $default_attributes;
}
// Hook into the ‘woocommerce_product_get_default_attributes’ filter
add_filter(‘woocommerce_product_get_default_attributes’, ‘set_default_quantity_attribute’, 10, 2);
// Function to get the user’s role
function get_user_role() {
if (is_user_logged_in()) {
$user = wp_get_current_user();
$user_roles = $user->roles;
if (in_array(‘reseller’, $user_roles) || in_array(‘administrator’, $user_roles)) {
return ‘reseller’; // Both resellers and administrators will trigger this condition
}
}
// Default to no specific role for non-logged-in users and other roles
return ”;
}
​
[ad_2]