WooCommerce specifc variations for specific user role

i want to make a product variation that only can be seen by specific user roles.
I tried this code but it didnt work for me…

Can someone help me?

function user_has_role( $role, $user_id = null ) {

if ( is_numeric( $user_id ) )
$user = get_userdata( $user_id );
else
$user = wp_get_current_user();

if ( empty( $user ) )
return false;

return in_array( $role, (array) $user->roles );}

if ( taxonomy_exists( $name ) ) {
$terms = wc_get_product_terms( $post->ID, $name, array( ‘fields’ => ‘all’ ) );
foreach ( $terms as $term ) {
if ( ! in_array( $term->slug, $options ) ) {
continue;
}
if($name == ‘ermaessigt’ && $term->slug != ‘normal’ ) { // or whatever your attribute is called, and whatever the attribute term is called.
if(!user_has_role(‘administrator’)){
continue;
}
}
echo ‘<option value=”‘ . esc_attr( $term->slug ) . ‘” ‘ . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . ‘>’ . apply_filters( ‘woocommerce_variation_option_name’, $term->name ) . ‘</option>’;
}
} else {
foreach ( $options as $option ) {
if($name == ‘pa_weight’ && $option != ‘1kg’ ) { // or whatever your attribute is called, and whatever the attribute term is called.
if(!user_has_role(‘aziende’)){
continue;
}
}

echo ‘<option value=”‘ . esc_attr( sanitize_title( $option ) ) . ‘” ‘ . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . ‘>’ . esc_html( apply_filters( ‘woocommerce_variation_option_name’, $option ) ) . ‘</option>’;
}
}

Read more here:: WooCommerce specifc variations for specific user role

Leave a Reply

Your email address will not be published. Required fields are marked *