I need to prevent selling more than 30 items per day by IP address in woocommerce. Basically, it is protection from bots. I think logic must be something like this:
*user registration is disabled
So I'm not sure where to start and how to follow to woocommerce hooks rules.
Any code examples would be highly appreciated
WooCommerce actually stores client IP addresses in the order metadata by default. You can use the get_customer_ip_address()
method on a WC_Order
to access this metadata. Likewise, WooCommerce includes WC_Geolocation::get_ip_address()
to get the IP of the currently connected client.
Putting these together, you can use the woocommerce_checkout_process
hook to give an error if a user with the same IP tries to make too many purchases in the given time period.
Here I'm using wc_get_orders()
to succinctly query for all orders with a matching IP in the last 24 hours, and cancel the transaction if there are more than 30 results.
function my_ip_checker() {
$last_24_hours_from_ip_results = wc_get_orders(array(
'date_created' => '>=' . (time() - 86400), // time in seconds
'customer_ip_address' => WC_Geolocation::get_ip_address(),
'paginate' => true // adds a total field to the results
));
if($last_24_hours_from_ip_results->total > 30) {
wc_add_notice('Too many orders in the last 24 hours. Please return later.', 'error');
}
}
add_action('woocommerce_checkout_process', 'my_ip_checker', 10, 0);
Note that the call to wc_add_notice()
with a type of 'error'
will stop the transaction from going through.