Amanda Anderson
Amanda Anderson

Reputation: 1

Hide HTML element if user role and product conditions are met

I'm looking to do the following condition. If a user has a user role of "Customer" and they have any product id of 1, 2, or 3 in the cart, then a specific shipping option would not show for that user. I have this started:

<?php 
 $user = wp_get_current_user();
 if ('vendor', $user->roles ) {
 ?>

I'm not sure how to proceed from here.

Upvotes: 0

Views: 469

Answers (1)

bhanu
bhanu

Reputation: 1860

You can simply do that like this.

function matched_cart_items( $search_products ) {
    $count = 0; // Initializing

    if ( ! WC()->cart->is_empty() ) {
        // Loop though cart items
        foreach(WC()->cart->get_cart() as $cart_item ) {
            // Handling also variable products and their products variations
            $cart_item_ids = array($cart_item['product_id'], $cart_item['variation_id']);

            // Handle a simple product Id (int or string) or an array of product Ids 
            if( ( is_array($search_products) && array_intersect($search_products, cart_item_ids) ) 
            || ( !is_array($search_products) && in_array($search_products, $cart_item_ids)
                $count++; // incrementing items count
        }
    }
    return $count; // returning matched items count 
}

// to Search Cart
if ( in_array( 'customer', (array) wp_get_current_user()->roles ) && (0 < matched_cart_items( 1, 2,3 )) ) {
 // Do your thing.
}

A part of this answer has been picked up from here : https://stackoverflow.com/a/41266005/8298248

Upvotes: 0

Related Questions