I'm trying to stop customers buying a certain product more than once, even if they aren't logged in.
I've tried a few different functions.
<?php
add_action('woocommerce_after_checkout_validation', custom_after_checkout_validation');
function custom_after_checkout_validation( $posted ) {
$address = $order->get_billing_address_1();
$email = $order->get_billing_email();
// Set HERE ine the array your specific target product IDs
$prod_arr = array( '19861', '19908' );
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_billing_email',
'meta_value' => $email,
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-completed' // Only orders with status "completed"
) );
foreach ( $customer_orders as $customer_order ) {
// Updated compatibility with WooCommerce 3+
//$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;----------------
$orders = wc_get_order( $customer_order );
foreach ($orders as $order2) {
$address2 = $order->get_billing_address_1();
foreach($order2->get_items() as $item){
// WC 3+ compatibility
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
$product_id = $item['product_id'];
}
else {
$product_id = $item->get_product_id();
}
// Your condition related to your 2 specific products Ids
if ( in_array( $product_id, $prod_arr ) ) {
if ($address == $address2) {
wc_add_notice( __( "You have already purchased this product.", 'woocommerce' ), 'error' );
}
}
}
}
}
}
?>
This one is returning an internal server error. Please Help! TIA