为什么我不能从 Woocommerce 结帐字段中检索数据以在订单处理过程中更新订阅数据?
我想根据客户在结账时的频率请求更新下一个续订日期。这是我的代码:
1)设置结帐字段:
add_action( 'woocommerce_after_order_notes', 'hgf_custom_checkout_field' );
function hgf_custom_checkout_field( $checkout ) {
global $woocommerce;
woocommerce_form_field( 'frequency', array(
'type' => 'select',
'required' => true,
'class' => array('form-row-wide'),
'label' => __('Change this any time, just email.'),
'options' => array(
'blank' => __( 'Select frequency preference', 'woocommerce' ),
1 => __( 'Every Week', 'woocommerce' ),
2 => __( 'Every Other Week' , 'woocommerce' ),
3 => __( 'Once Per Month' , 'woocommerce' )
)
), $checkout->get_value( 'frequency' ));
echo '</div>';
}
2)更新订单元。这会在客户订单上创建两个自定义字段,并更新订阅的计费间隔:
add_action( 'woocommerce_checkout_update_order_meta', 'hgf_checkout_field_update_order_meta' );
function hgf_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['frequency'] ) ) {
update_post_meta( $order_id, 'frequency', $_POST['frequency'] );
update_post_meta( $order_id, 'billing_interval', $_POST['frequency'] );
}
}
3)更新更新日期
对于最后一部分,我可以用我选择的虚拟日期更新更新日期(例如:$renewal date = "2018-12-15"
,但是当我尝试让它读取该'billing_interval'
字段时,它会恢复为else
默认值。
add_action( 'woocommerce_checkout_create_subscription', 'hgf_next_renewal' );
function hgf_next_renewal( $subscription, $timezone='site' ) {
$billing_interval = get_post_meta( get_the_ID(), 'billing_interval', true);
if( $billing_interval == 2 ) {
$renewal_date = date( 'Y-m-d H:i:s', strtotime( "2017-10-01" ) ) /* date( 'Y-m-d H:i:s', strtotime( "+2 weeks" ) ) */ ;
} if( $billing_interval == 4 ) {
$renewal_date = date( 'Y-m-d H:i:s', strtotime( "2017-12-01" ) ) /* date( 'Y-m-d H:i:s', strtotime( "+4 weeks" ) ) */ ;
} else {
$renewal_date = date( 'Y-m-d H:i:s' ) ) /* date( 'Y-m-d H:i:s', strtotime( $renewal_date) ) */ ;
}
$subscription->update_dates( array(
'next_payment' => $renewal_date,
) );
return $subscription;
}
这是我尝试过的所有不同方法:
1) $billing_interval = $subscription->get_billing_interval();
2) $billing_interval = get_post_meta( $subscription->get_ID(), 'billing_interval', true);
3) $billing_interval = get_post_meta( $order_id, 'billing_interval', true);
4) $subscriptions = wcs_get_users_subscriptions( $user_id );
foreach ( $subscriptions as $sub ) {
$billing_interval = get_post_meta( $sub->get_order_number(), '_billing_interval', true);
}
5) $billing_interval = $checkout->get_value( 'frequency' );
有谁知道为什么我在'woocommerce_checkout_create_subscription'
操作时无法从结帐字段中检索值?