• Resolved hellboy123

    (@hellboy123)


    Hi there. Is there a code snippet that can apply a filter to restrict WC vendors from purshasing their own products from the shop?

Viewing 1 replies (of 1 total)
  • Thread Starter hellboy123

    (@hellboy123)

    I suppose that your “post authors” (vendors) have a custom role (or some specific capabilities). So you can target the user role “post authors” (or one of his specifics capabilities) checking and removing cart items on checkout page for this user roles.

    Here is that code:

    add_action( 'woocommerce_before_checkout_form', 'checking_allowed_cart_items_on_checkout', 100, 1);
    function checking_allowed_cart_items_on_checkout() {
    
        // Allow only "administrator" and "customer" user roles to buy all products
        if( ! current_user_can('administrator') || ! current_user_can('customer') ){
    
            // Ititializing variables
            $found = false;
            $cart_object = WC()->cart;
            $current_user_id = get_current_user_id();
    
            // Checking cart items
            foreach($cart_object->get_cart() as $cart_item_key => $cart_item){
                // get the WC_Product object and the product ID
                $product = $cart_item['data'];
                $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
    
                // Get the product post object to get the post author
                $post_obj = get_post( $product_id );
                $post_author = $post_obj->post_author;
    
                if( $post_author == $current_user_id ){
                    // removing the cart item
                    $cart_object->remove_cart_item( $cart_item_key );
                    $found = true; // set to true if a product of this author is found
                }
            }
    
            // Display a custom message in checkout page when items are removed
            if( $found ){
                // Display an error message
                wc_add_notice( __( 'Items removed - As a Vendor, you are not allowed to buy your own products.' ), 'error' );
            }
        }
Viewing 1 replies (of 1 total)
  • The topic ‘Restrict WC Vendors purchasing own products’ is closed to new replies.