【发布时间】:2017-11-26 17:16:25
【问题描述】:
我正在使用 WooCommerce 会员资格,如果首次购买特定产品的会员,我想将免费会员资格提供给他们。我可以让其中一些单独工作,但无法将它们全部组合在一起。
他们必须购买的商品也有销售价格,因此我也在检查日期以查看该商品是否在销售窗口中。那部分正在工作。
似乎当我添加参数以检查商品是否在购物车中时,整个事情都中断了。如果我分别运行这两个函数,它们都可以工作。
function mps_registration_price($cart_object) {
global $post, $product;
// Bail if memberships is not active
if ( ! function_exists( 'wc_memberships' ) ) {
return;
}
$user_id = get_current_user_id();
date_default_timezone_set("America/Chicago");
$today = time();
// Check if user was never a member
if ( !wc_memberships_get_user_memberships( $user_id )) {
if( mps_check_for_product() ) {
foreach ( $cart_object->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$id = $cart_item['data']->get_id();
if($id == 17) {
$salePrice = get_post_meta($id, '_sale_price', true);
$saleFrom = get_post_meta($id, '_sale_price_dates_from', true);
$saleTo = get_post_meta($id, '_sale_price_dates_to', true);
if( !empty($salePrice) && $today >= $saleFrom && $today <= $saleTo ) {
$new_price = $salePrice;
} else {
$new_price = get_post_meta($id, '_regular_price', true);
}
// Updated cart item price
$cart_item['data']->set_price( $new_price );
}
}
} else {
foreach ( $cart_object->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$id = $cart_item['data']->get_id();
if($id == 17) {
$salePrice = get_post_meta($id, '_sale_price', true);
$saleFrom = get_post_meta($id, '_sale_price_dates_from', true);
$saleTo = get_post_meta($id, '_sale_price_dates_to', true);
if( !empty($salePrice) && $today >= $saleFrom && $today <= $saleTo ) {
$new_price = $salePrice + 50;
} else {
$new_price = get_post_meta($id, '_regular_price', true);
}
// Updated cart item price
$cart_item['data']->set_price( $new_price );
}
}
}
}
}
add_filter( 'woocommerce_before_calculate_totals', 'mps_registration_price', 10, 1 );
function mps_check_for_product() {
$product_id = 11;
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart ) {
return true;
} else {
return false;
}
}
add_action('woocommerce_before_cart', 'mps_check_for_product');
【问题讨论】:
标签: php wordpress woocommerce cart membership