我正在尝试根据产品变体和将产品添加到购物车时选择的自定义字段选项的组合来动态设置订阅试用期。
对于一种产品版本,可以选择立即付款,也可以将第一笔付款推迟到新的一年开始。通过自定义单选按钮字段选择该选项。对于所有其他产品变体,付款将自动延迟。
使用
为产品本身设置默认试用长度就足够简单了add_filter( 'woocommerce_subscriptions_product_trial_length', 'stc_woocommerce_subscriptions_product_trial_length', 10, 2 );
function stc_woocommerce_subscriptions_product_trial_length( $subscription_trial_length, $product ){
// Do the calculations based on the current date, product_id, &c. and return a revised $subscription_trial_length as needed
}
但是我不知道如何将“立即付款”选项的trial_length设置为零。
用于设置/更新subscription_trial_length的最有可能的工具似乎是wcs_set_objects_property
,尽管我已经尝试了很多其他方法。我只是一直绕圈转。
这是我正在使用的功能的简化版本:
function make_my_cart_revisions( $cart_obj ) {
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) ) { return; }
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) { return; }
foreach( $cart_obj->get_cart() as $cart_item) {
// First check to see if the cart item is a subscription product or a variation thereof. Skip any other items.
if ( is_a( $cart_item['data'], 'WC_Product_Subscription' ) || is_a( $cart_item['data'], 'WC_Product_Subscription_Variation' ) ) {
$subscription_trial_length = WC_Subscriptions_Product::get_trial_length( $cart_item['data'] );
$pa_pledge_year = $cart_item['variation']['attribute_pa_pledge_year'];
$pledge_year = substr($pa_pledge_year, 0, 4);
$current_year = date("Y"); // numeric representation of current year, four digits
$billing_period = $cart_item['variation']['attribute_pa_billing_period'];
$pledge_payment_schedule = $cart_item['pledge_payment_schedule']; // Custom product field: "defer-payment" or "pay-immediately"
if ( $pledge_year !== $current_year && $billing_period == 'onetime-payment' && $pledge_payment_schedule == 'pay-immediately' && $subscription_trial_length > 0 ) {
$subscription_trial_length = 0;
// Trying to update the subscription length with the following:
wcs_set_objects_property( $cart_item['data'], 'subscription_trial_length', $subscription_trial_length, 'set_prop_only' );
// Also tried these different approaches to saving the revised trial length:
//$cart_item['data']->update_meta_data( '_subscription_trial_length', $subscription_trial_length );
//$cart_item['data']->set_subscription_trial_length( $subscription_trial_length );
}
} // end check for subscription product/variation
} // end foreach
}
我从调试日志中看到,正在根据cart_item详细信息计算出正确的subscription_trial_length,但是我为保存该值以使其在购物车总计中正确显示而进行的所有尝试均失败了。例如,我选择了“立即付款”选项的产品仍会显示在经常发生的总额中,但不会立即显示在应付金额中。
作为替代,我尝试不使用默认的trial_length,而是将带有延期付款选项的产品将其设置为非零金额(从而省去了挂接到woocommerce_subscriptions_product_trial_length
过滤器的步骤),但是问题是仍然存在:我无法获取新的trial_length值来成功设置cart_item。
任何帮助将不胜感激!