woocommercehideadditioncart

A notice message to users who have bought a product on Woocommerce


Hiding the Add to cart button, after a user get a product.

// Woocommerce Product bought Once
add_filter('woocommerce_add_to_cart_validation','sd_bought_before_woocommerce_add_to_cart_validation',20, 2);
function sd_bought_before_woocommerce_add_to_cart_validation($valid, $product_id){
 $current_user = wp_get_current_user();
 if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id)) {
 wc_add_notice( __( 'You can only get this free product once.Thanks', 'woocommerce' ), 'error' );
 $valid = false;
 }
 return $valid;
}


Solution

  • Try using the woocommerce_is_purchasable filter hook to hide the add to cart button:

    Example:

    function sd_bought_before_woocommerce_add_to_cart_validation( $is_purchasable, $instance ){
        
        $current_user = wp_get_current_user();
        if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $instance->get_id()) ) {
            $is_purchasable = false;
        }
        return $is_purchasable;
    }
    add_filter( 'woocommerce_is_purchasable', 'sd_bought_before_woocommerce_add_to_cart_validation', 10, 2 );
    

    More info: http://hookr.io/filters/woocommerce_is_purchasable/