Reputation: 1
I am creating an LMS using LearnDash + WooCommerce. I am trying to find a way to hide specific product from the Woocommerce product table page. If the logged in user has already purchased said product a) prevent the user from purchasing it twice, and b) so that I can display a product grid for them without the already purchased item(s).
Another example: if a user who purchased Item B and D goes to the shop, Item B and D should not even be displayed for them.
+--------+----------+
| Item A | $116 |
+--------+----------+
| Item B | $96 |
+--------+----------+
| Item C | $41 |
+--------+----------+
| Item D | $78 |
+--------+----------+
↓
+--------+----------+
| Item A | $116 |
+--------+----------+
| Item C | $41 |
+--------+----------+
This is my code:
/* Avoid buying the same product again in WooCommerce by adding products to the cart by logged-in users before checkout */
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null) {
// Retrieve the current user object
$current_user = wp_get_current_user();
// Check for variantions, if you don't want this, delete this code line
$product_id = $variation_id > 0 ? $variation_id : $product_id;
// Checks if a user (by email or ID or both) has bought an item
if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) {
// Display an error message
wc_add_notice( __( 'You have already enrolled into the course. ' , 'woocommerce' ), 'error' );
$passed = false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
So any help would be appreciated.
Upvotes: 0
Views: 840
Reputation: 11282
You can change the product query using the pre_get_posts
action hook and then you can get current user products that they already purchased. pass all products id to post__not_in
. check the below code. code will go active theme function.php file.
add_action( 'pre_get_posts', 'hide_product_from_shop_page_if_user_already_purchased', 20 );
function hide_product_from_shop_page_if_user_already_purchased( $query ) {
if ( ! $query->is_main_query() ) return;
if ( ! is_admin() && is_shop() ) {
$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) return;
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => $current_user->ID,
'post_type' => 'shop_order',
'post_status' => array( 'wc-processing', 'wc-completed' ),
) );
if ( ! $customer_orders ) return;
$product_ids = array();
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order->ID );
if( $order ){
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$product_ids[] = $product_id;
}
}
}
$product_ids = array_unique( $product_ids );
$query->set( 'post__not_in', $product_ids );
}
}
Upvotes: 1