Search code examples
phpwordpresswoocommerceproductuser-roles

Prevent post-authors from buying and bidding their own products in WooCommerce


With WooCommerce, I am using WC Vendors Pro plugin + Rehub theme + Auction plugin (by wp giene) + Simple Auctions plugin (by WC Vendors).

How can I prevent post-authors from buying and bidding their own products in WooCommerce?

I don't want the post authors to bid on the products they have posted, to prevent price increases (which is not correct).

Where to start, any Ideas?

Thanks


Solution

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

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested and works.