<?php
/**
* Plugin Name: WooCommerce Prevent Repeat Purchases
* Description: Prevents customers from purchasing products they've already bought.
* Version: 1.0.0
* Author: Your Name
*/
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
/**
* Check if product was previously purchased before adding to cart
*/
function check_if_product_previously_purchased($passed, $product_id) {
// Skip check if user is not logged in
if (!is_user_logged_in()) {
return $passed;
}
$current_user_id = get_current_user_id();
// Get all customer orders
$customer_orders = wc_get_orders(array(
'customer_id' => $current_user_id,
'status' => array('wc-completed', 'wc-processing'),
'limit' => -1, // Get all orders
));
// Check each order to see if this product was previously purchased
foreach ($customer_orders as $order) {
foreach ($order->get_items() as $item) {
// If product ID matches the current product being added to cart
if ($item->get_product_id() == $product_id) {
// Product was previously purchased, prevent adding to cart
wc_add_notice(
sprintf(
__('You\'ve already purchased %s in a previous order (#%s). This product can only be purchased once.', 'woocommerce'),
get_the_title($product_id),
$order->get_order_number()
),
'error'
);
return false;
}
}
}
// Product hasn't been purchased before, allow adding to cart
return $passed;
}
add_filter('woocommerce_add_to_cart_validation', 'check_if_product_previously_purchased', 10, 2);
/**
* Display a notice on the product page if the customer has already purchased this product
*/
function display_already_purchased_notice() {
if (!is_user_logged_in() || !is_product()) {
return;
}
global $product;
$product_id = $product->get_id();
$current_user_id = get_current_user_id();
// Get all customer orders
$customer_orders = wc_get_orders(array(
'customer_id' => $current_user_id,
'status' => array('wc-completed', 'wc-processing'),
'limit' => -1, // Get all orders
));
// Check each order to see if this product was previously purchased
foreach ($customer_orders as $order) {
foreach ($order->get_items() as $item) {
// If product ID matches the current product
if ($item->get_product_id() == $product_id) {
// Display notice that product was previously purchased
wc_print_notice(
sprintf(
__('You\'ve already purchased this product in order #%s on %s. This product can only be purchased once.', 'woocommerce'),
$order->get_order_number(),
$order->get_date_created()->date_i18n(get_option('date_format'))
),
'notice'
);
return;
}
}
}
}
add_action('woocommerce_before_single_product', 'display_already_purchased_notice');
Comments
0 B
|👍
/👎
0 B
|👍
/👎