防止在woocommerce中重复购买产品

时间:2018-12-21 21:44:19

标签: php arrays woocommerce

我有多种产品需要,我需要阻止它们被重复购买,正如您从第一节下面的代码中看到的那样,使得产品无法购买

function sv_disable_repeat_purchase( $purchasable, $product ) {
// Enter the ID of the product that shouldn't be purchased again
$non_purchasable = 28385;


// Get the ID for the current product (passed in)
$product_id = $product->is_type( 'variation' ) ? $product->variation_id : $product->id;

// Bail unless the ID is equal to our desired non-purchasable product
if ( $non_purchasable != $product_id ) {
    return $purchasable;
}

// return false if the customer has bought the product
if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $product_id ) ) {
    $purchasable = false;
}

// Double-check for variations: if parent is not purchasable, then variation is not
if ( $purchasable && $product->is_type( 'variation' ) ) {
    $purchasable = $product->parent->is_purchasable();
}

return $purchasable;
}
add_filter( 'woocommerce_variation_is_purchasable', 
'sv_disable_repeat_purchase', 10, 2 );
add_filter( 'woocommerce_is_purchasable', 
'sv_disable_repeat_purchase', 10, 2 );

我的代码的这一部分向已经购买的人添加了一条消息

function sv_purchase_disabled_message() {
// Enter the ID of the product that shouldn't be purchased again
$no_repeats_id =  28385;
$no_repeats_product = wc_get_product( $no_repeats_id );

// Get the current product to check if purchasing should be disabled
global $product;

if ( $no_repeats_product->is_type( 'variation' ) ) {
    // Bail if we're not looking at the product page for the non-purchasable product
    if ( ! $no_repeats_product->parent->id === $product->id ) {
        return;
    }

    // Render the purchase restricted message if we are
    if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $no_repeats_id ) ) {
        sv_render_variation_non_purchasable_message( $product, $no_repeats_id );
    }

} elseif ( $no_repeats_id === $product->id ) {
    if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $no_repeats_id ) ) {
        // Create your message for the customer here
        echo '<div class="woocommerce"><div class="woocommerce-info wc-nonpurchasable-message">You\'ve already purchased this product! It can only be purchased once.</div></div>';
    }
}
}
add_action( 'woocommerce_single_product_summary', 'sv_purchase_disabled_message', 31 );

正如我所说的那样,此代码对于单个产品来说很好,但是我尝试添加数组

$non_purchasable = array('28385','12345','6789'); 

该产品仍可购买,因此我正在寻找一种添加阵列的方式,以使这些产品只能购买一次

0 个答案:

没有答案