在WooCommerce中,如果客户已购买产品(A或B),则在一个月内要禁用对定义产品(B,C和D)的购买,因此产品B,C和D应该只能对该特定用户禁用一个月。
注意:在下面的代码中,我正在使用has_bought_items()
来自 Check if a user has purchased specific products in WooCommerce 答案的自定义函数。
我的代码尝试:
$product_ids = array( 255, 256 );
$args2 = array(
'customer_id' => get_current_user_id()
);
$orders = wc_get_orders( $args2 );
$orders = has_bought_items( get_current_user_id(), $product_ids );
if($orders){
add_filter('woocommerce_is_purchasable', 'disable_product', 10, 2 );
function disable_product( $is_purchasable, $product ) {
if( in_array( $product->get_id(), array( 256, 257, 258 ) ) ) {
return false;
}
return $is_purchasable;
}
}
So far I am able to disable the products for the user. But I don't how can I get date from the purchase and add a month to it. Any help will be great.
答案 0 :(得分:1)
您需要对has_bought_items()
中的代码进行一些自定义,以从已购买产品ID 255
或256
(对于当前用户)的客户订单中获得最高的“发布日期” ID)。
然后使用strtotime()
功能,您将可以在一个月内禁用对其他定义产品的购买。
使用自定义SQL查询的代码:
add_filter('woocommerce_is_purchasable', 'disable_specific_product_conditionally', 10, 2 );
function disable_specific_product_conditionally( $is_purchasable, $product ) {
$targeted_ids = array( 256, 257, 258 ); // Related targeted products to be disabled
if( in_array( $product->get_id(), $targeted_ids ) && is_user_logged_in() ) {
global $wpdb;
$product_ids = array( 255, 256 ); // Check orders for this products
// Count the number of products
$date = $wpdb->get_var("
SELECT p.post_date FROM {$wpdb->prefix}posts AS p
INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
WHERE p.post_status IN ( 'wc-" . implode( "','wc-", array_map( 'esc_sql', wc_get_is_paid_statuses() ) ) . "' )
AND pm.meta_key = '_customer_user'
AND pm.meta_value = '".get_current_user_id()."'
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value IN (".implode(',', $product_ids).")
ORDER BY p.post_date DESC
");
// When a date is found we disable during a month purchases from this date
return ! empty($date) && strtotime('now') > strtotime( $date . ' + 1 month') ? false : $is_purchasable;
}
return $is_purchasable;
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。