首頁 >後端開發 >php教程 >如何透過要求客戶提供先前購買的證明來防止在 WooCommerce 中未經授權購買特定產品?

如何透過要求客戶提供先前購買的證明來防止在 WooCommerce 中未經授權購買特定產品?

DDD
DDD原創
2024-11-14 19:57:02600瀏覽

How can I prevent unauthorized purchases of specific products in WooCommerce by requiring customers to have proof of a prior purchase?

對WooCommerce 中防止未經授權的購買做出反應

問題:

商家面臨著防止特定商品未經授權購買的常見挑戰產品。在這種情況下,客戶必須擁有產品「a」或「b」的先前購買證明才能存取產品「c」、「d」和「e」。

解決方案:

在本綜合指南中,我們將為您提供自訂功能,用於確定客戶在啟用存取受限商品之前是否購買了必備產品。

function has_bought_items() {
    $bought = false;

    // Replace the numbers with your specific target product IDs
    $prod_arr = array( '21', '67' );

    // Gather all customer orders
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => 'shop_order', // WooCommerce orders post type
        'post_status' => 'wc-completed' // Only orders with "completed" status
    ) );

    // Process each customer order
    foreach ( $customer_orders as $customer_order ) {
        // Handle WooCommerce version compatibility
        $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
        $order = wc_get_order( $customer_order );

        // Iterate through products bought in the order
        foreach ($order->get_items() as $item) {
            // Product ID retrieval based on WooCommerce version
            if ( version_compare( WC_VERSION, '3.0', '<' ) ) 
                $product_id = $item['product_id'];
            else
                $product_id = $item->get_product_id();

            // Condition: Check if required product ID exists in the array of purchased products
            if ( in_array( $product_id, $prod_arr ) ) 
                $bought = true;
        }
    }

    // Return true if the specific products have been purchased by the customer
    return $bought;
}

使用:

在 WooCommerce在範本中實作操作產品加入購物車按鈕的功能,例如:

  • Loop/add-to-cart.php商店頁面
  • 單一產品頁面的單一產品/新增至購物車資料夾

例如,在商店頁面的加入到購物車按鈕範本中(循環/ add-to-cart.php):

// Replace numbers with restricted product IDs
$restricted_products = array( '20', '32', '75' );

// WooCommerce compatibility adjustment
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

// Restricted product, inactive add-to-cart button
if ( !has_bought_items() && in_array( $product_id, $restricted_products ) ) { 

    // Display an inactive add-to-cart button with a custom message

// Non-restricted product or allowed product after specific purchase
} else { 

    // Regular add-to-cart button code
}

此範例動態停用特定產品的「加入購物車」按鈕,直到顧客證明之前購買了所需商品。

以上是如何透過要求客戶提供先前購買的證明來防止在 WooCommerce 中未經授權購買特定產品?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn