用购物车总数和订阅期替换 WooCommerce "Place order" 按钮文本

Replace WooCommerce "Place order" button text with cart total and subscription period

我正在使用以下代码专门针对基于订阅的产品。

// Display total amount on place order button
add_filter('woocommerce_order_button_text', 'subscriptions_custom_checkout_submit_button_text' );
function subscriptions_custom_checkout_submit_button_text( $order_button_text ) {
if ( WC_Subscriptions_Cart::cart_contains_subscription() ) {
    $cart_total = WC()->cart->total;    
return __('Pay $' . $cart_total, 'woocommerce');
    
} else {
    // You can change it here for other products types in cart
    # $order_button_text =  __( 'Something here', 'woocommerce-subscriptions'  );
}
return $order_button_text;
}

现在,我想在产品价格后显示订阅期,例如,如果有人购买按月订阅的产品,按钮应显示为(每月支付 20 美元)。

使用以下方法在结帐页面上获取自定义“下订单”按钮,当购物车中只有订阅产品时,在提交按钮上显示购物车总数和订阅期:

add_filter('woocommerce_order_button_text', 'subscriptions_custom_checkout_submit_button_text' );
function subscriptions_custom_checkout_submit_button_text( $button_text ) {
    if ( WC_Subscriptions_Cart::cart_contains_subscription() ) {
        $cart  = WC()->cart;
        $total = $cart->total;
        $other = false;

        // Loop through cart items
        foreach ( $cart->get_cart() as $item )  {
            $product = $item['data'];
            if( in_array( $product->get_type(), ['subscription', 'subscription_variation'] ) ) {
                $period = get_post_meta( $product->get_id(), '_subscription_period', true );
            } else {
                $other = true; // There are other items in cart
            }
        }
        // When there are only Subscriptions in cart
        if ( isset($period) && ! $other ) {
            return sprintf( __('Pay %s/%s' , 'woocommerce'), strip_tags( wc_price($total) ), ucfirst($period) );
        }
    }
    return $button_text;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。