Jack Torris
Jack Torris

Reputation: 804

Woocommerce product variation based on user role

I've set up Woocommerce with variable products.

These products all have variations on an attribute with the possible values of 1kg, 2kg, and 5kg.

I've also created an "Aziende" user group. I want some product variations to only display for "Aziende" customers. I don't want these variations visible to other customers.

For example: Aziende Customers see the options "1kg, 2kg, 5kg", While other customer roles only see the 1kg option.

Is this possible in Woocommerce?

Upvotes: 0

Views: 3363

Answers (1)

larsemil
larsemil

Reputation: 876

Yes. If you override the file woocommerce/templates/single-product/add-to-cart/variable.php you find the code for the variations selectbox.

There you could do something like:

First of all I always include this snippet when working with roles:

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 );
}

So it can be used as:

if(user_has_role("Aziende")){
    //do stuff
}

Now having this function, and knowing which template to change you should be able to do something in that file. It could be along this:

// Get terms if this is a taxonomy - ordered
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 == 'pa_weight' && $term->slug != '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( $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>';
    }
}

This code is not tested, so I dont know if it works. But it should give you a pointer in the correct direction.

Upvotes: 1

Related Questions