Woocommerce:如果客户已经购买了此产品,则隐藏“添加到购物车”按钮

时间:2020-09-08 11:47:17

标签: woocommerce

如果客户已经购买了该产品(按照他之前的所有订单),我想在商店页面上隐藏“添加到购物车”按钮,在这种情况下,我想代替按钮。我已经找到该脚本here

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的方式有问题吗? 还是有更好的方法来达到预期的结果?

谢谢!

1 个答案:

答案 0 :(得分:1)

我最终使用了the built-in function 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";