douluoqiu4538 2019-05-20 10:16 采纳率: 100%
浏览 72

只允许客户购买某种产品,即使他们没有登录

I'm trying to stop customers buying a certain product more than once, even if they aren't logged in.

I've tried a few different functions.

<?php 
    add_action('woocommerce_after_checkout_validation',    custom_after_checkout_validation');

    function custom_after_checkout_validation( $posted ) {
    $address = $order->get_billing_address_1();
    $email = $order->get_billing_email();
    // Set HERE ine the array your specific target product IDs
    $prod_arr = array( '19861', '19908' );

    // Get all customer orders
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_billing_email',
        'meta_value'  => $email,
        'post_type'   => 'shop_order', // WC orders post type
        'post_status' => 'wc-completed' // Only orders with status    "completed"
       ) );
        foreach ( $customer_orders as $customer_order ) {
        // Updated compatibility with WooCommerce 3+
        //$order_id = method_exists( $order, 'get_id' ) ? $order->get_id()   : $order->id;----------------
        $orders = wc_get_order( $customer_order );
        foreach ($orders as $order2) {
            $address2 = $order->get_billing_address_1();

            foreach($order2->get_items() as $item){
                // WC 3+ compatibility
                if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
                    $product_id = $item['product_id'];
                }
                else {
                    $product_id = $item->get_product_id();
                }

                // Your condition related to your 2 specific products Ids
                if ( in_array( $product_id, $prod_arr ) ) {
                    if ($address == $address2) {
                        wc_add_notice( __( "You have already purchased    this product.", 'woocommerce' ), 'error' );
                    }
                }
            }
           }
        }
      }
?>

This one is returning an internal server error. Please Help! TIA

  • 写回答

1条回答 默认 最新

  • dooo61733 2019-05-20 12:29
    关注

    You're passing a variable named $posted and inside the function you're using the $order class, which is not defined.

    Change $posted to $order in the fourth line and it should work.

    Edit: If it still doesn't work, the function may gets passed just the order-id instead of the class. In this case you could insert $order = wc_get_order( $posted ); after line four.

    评论

报告相同问题?