如果产品已经购买,请从Woocommerce商店页面隐藏产品



我正试图找到一种方法来从Wooccommerce商店页面隐藏产品。如果登录的用户已经购买了所述产品。

我已经能够阻止用户使用woocommerce_is_purchasablewoocommerce_variation_is_purchasable再次购买。但我想把它藏在一起,甚至不在商店页面上显示给他们。我在这个问题上一直是空的。因此,任何帮助都将不胜感激。

您可以使用pre_get_posts操作挂钩更改产品查询,然后您可以获得当前用户已经购买的产品。将所有产品id传递给post__not_in。检查以下代码。代码将进入活动主题函数.php文件。

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 );
}
}
根据所问问题,Bhautik的回答在技术上是正确的。如果用户以前购买过,请隐藏产品。

然而,正如我在问题中提到的,我已经禁止使用woocommerce_is_purchasable购买上述产品。

这意味着应该隐藏的逻辑已经在软件中了。使用他的想法作为模板,我使答案更通用,可以在woocommerce_is_purchasable之外操作。这意味着我只需要在该函数中实现任何条件逻辑,商店就会通过隐藏所述产品(无法购买(来进行反映。

我将此作为第二个答案发布,以防它帮助其他人搜索此问题。但将保留他作为问题的选定答案。

add_action( 'woocommerce_product_query', 'hide_product_from_shop_page_if_user_already_purchased', 20 );
function hide_product_from_shop_page_if_user_already_purchased( $query ) {
//Get all the products in the store.
$products = wc_get_products(['limit' => -1]);
//Blank exclusion array. 
$product_ids = array();
//Check each product to see if it is purchasable or not.
foreach($products as $product){
if(!$product->is_purchasable()){
//If product is not purchasable then add to exclusion array.
$product_ids[] = $product->get_id();
}
}
//Use array of id's to exclude products in the shop page.
$query->set( 'post__not_in', $product_ids );
}

最新更新