Woocommerce Preselected Attribute based on role

[ad_1]

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]

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer