我在 WooCommerce 网站上有订阅。我创建了一项功能,如果有有效订阅,则在购买时将其重写为新订阅:
add_action( 'woocommerce_thankyou', 'cancel_previous_active_subscription' );
function cancel_previous_active_subscription() {
$no_of_loops = 0;
$user_id = get_current_user_id();
$args = array(
'subscription_status' => 'active',
'subscriptions_per_page' => -1,
'customer_id' => $user_id,
'orderby' => 'ID',
'order' => 'DESC'
);
$subscriptions = wcs_get_subscriptions($args);
foreach ( $subscriptions as $subscription ) {
$no_of_loops = $no_of_loops + 1;
if ($no_of_loops > 1){
$subscription->update_status( 'cancelled' );
}
}
}
现在我们需要确保在结账时,如果有订阅,会显示一条通知。但仅限于结账时订阅,不适用于其他产品。现在,我的代码无法工作。怎么解决?
add_action( 'woocommerce_before_cart', 'display_subscription_notice' );
function display_subscription_notice() {
$user_id = get_current_user_id();
$args = array(
'subscription_status' => 'active',
'subscriptions_per_page' => 1,
'customer_id' => $user_id,
);
$subscriptions = wcs_get_subscriptions($args);
$has_subscription = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( wcs_order_contains_subscription( $cart_item['data']->get_id() ) ) {
$has_subscription = true;
break;
}
}
if ( !empty($subscriptions) && $has_subscription ) {
wc_add_notice( 'By purchasing a new subscription you will cancel your current one', 'notice' );
}
}
我有一个工作代码版本,但它绝对适用于所有产品,而且我只在购买新订阅时才需要它:
add_action('woocommerce_before_cart', 'display_subscription_notice');
function display_subscription_notice()
{
$user_id = get_current_user_id();
$args = array(
'subscription_status' => 'active',
'subscriptions_per_page' => 1,
'customer_id' => $user_id,
);
$subscriptions = wcs_get_subscriptions($args);
if (!empty($subscriptions)) {
wc_add_notice('By purchasing a new subscription you will cancel your current one', 'notice');
}
}
当订阅产品位于购物车并且客户已经有有效订阅时,您可以使用以下命令在结帐页面中显示通知:
// Conditional function: Check if a user has active subscriptions
function has_active_subscriptions( $user_id = 0 ) {
return wcs_user_has_subscription( $user_id > 0?:get_current_user_id(), '', 'active' );
}
// Conditional function: Check if a user has a subscription product in cart
function has_subscription_in_cart( $cart_contents = null ) {
foreach ( $cart_contents?:WC()->cart->get_cart() as $item ) {
if ( $item['data']->is_type( array('subscription', 'subscription_variation') ) ) {
return true;
}
}
return false;
}
// Display a notice in checkout conditionally
add_action( 'template_redirect', 'display_checkout_subscription_notice' );
function display_checkout_subscription_notice() {
if ( is_checkout() && ! is_wc_endpoint_url() && has_active_subscriptions() && has_subscription_in_cart() ) {
wc_add_notice( __('By purchasing a new subscription you will cancel your current active one.'), 'notice' );
}
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。
在结账页面(如果用户有有效订阅并且购物车中有订阅产品):