I’m trying to hide the variations of a product that have been purchased by a customer.
I found this piece of code that works but it hides the product itself and not just the variations that have been purchased.
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 );
}
}
How should I edit it so that it hides the variations of the product instead of the product itself?
Thanks!