我试图阻止客户多次购买某种产品,即使他们没有登录。
我尝试了几种不同的功能。
<?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' );
}
}
}
}
}
}
?>
此错误返回内部服务器错误。请帮忙! TIA
答案 0 :(得分:0)
您要传递一个名为"
的变量,并且在函数中使用的是[^;"\r\n]
类(未定义)。
在第四行中将$posted
更改为$order
,它应该可以工作。
编辑:如果仍然无法正常运行,则该函数可能仅传递了订单ID而不是类。在这种情况下,您可以在第四行之后插入$posted
。