Wooccommerce:如果客户已经购买了该产品,则隐藏"添加到购物车"按钮



如果客户已经购买了此产品(在他以前的所有订单中(,我想在商店页面上隐藏"添加到购物车"按钮,在这种情况下,我想用通知代替按钮。我在这里找到了这个脚本

add_shortcode( 'my_purchased_products', 'bbloomer_products_bought_by_curr_user' );
function bbloomer_products_bought_by_curr_user() {
// GET CURR USER
$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) return;
// GET USER ORDERS (COMPLETED + PROCESSING)
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key'    => '_customer_user',
'meta_value'  => $current_user->ID,
'post_type'   => wc_get_order_types(),
'post_status' => array_keys( wc_get_is_paid_statuses() ),
) );
// LOOP THROUGH ORDERS AND GET PRODUCT IDS
if ( ! $customer_orders ) return;
$product_ids = array();
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order->ID );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$product_ids[] = $product_id;
}
}
$product_ids = array_unique( $product_ids );
$product_ids_str = implode( ",", $product_ids );
// PASS PRODUCT IDS TO PRODUCTS SHORTCODE
return do_shortcode("[products ids='$product_ids_str']");

}

它工作得很好,它在$product_ids或$product_ids_str中收集以前的产品。

现在我想在循环中使用它,找出每个产品的ID是否是$product_ids数组的一部分。我已在商店页面中添加了短代码[my_purchased_products]。

在复制的模板文件archive-product.php或content-product.php中,我想使用$product_ids数组,或者字符串$product_ids_str,所以我从更改了脚本的最后一行

return do_shortcode("[products ids='$product_ids_str']");

return $product_ids;

return $product_ids_str;

但是,尽管脚本运行良好,但我无法访问结果,var_dump((给出NULL。

我返回$product_ids或$product_ids_str的方式有问题吗?还是有更好的方法来达到预期的结果?

提前感谢!

我最后使用了内置函数wc_customer_bought_product(),如下所示:

$pid = get_the_ID(); 
$uid = get_current_user_id();
if( wc_customer_bought_product('', $uid, $pid ) )
echo "already bought";
else
echo "not bought yet";

最新更新