无法从 WooCommerce 结帐中保存自定义复选框值

我创建了一个功能,可以在结算表格后将复选框添加到 WooCommerce 结帐中。


出现复选框,前端一切正常。


add_filter( 'woocommerce_after_checkout_billing_form' , 'add_field_sendy_woocommerce_agree', 9);


function add_field_sendy_woocommerce_agree( ) {


    woocommerce_form_field( 'sendy_woocommerce_agree', array(

    'type'          => 'checkbox',

    'label'         => __('Subscribe to our Newsletter.'),

    'required'  => false,

    'default' => 1 

    ),  WC()->checkout->get_value( 'sendy_woocommerce_agree' ));                               

}

问题是复选框没有保存为元数据。在wp_postmeta表中,_sendy_woocommerce_agree提交后缺少元键。


所以我无法访问它$xyz = $order->get_meta( '_sendy_woocommerce_agree' );


我究竟做错了什么?


幕布斯7119047
浏览 93回答 1
1回答

蝴蝶不菲

通过以下方式尝试一下function add_field_sendy_woocommerce_agree( $checkout ) {&nbsp; &nbsp; woocommerce_form_field( 'sendy_woocommerce_agree', array(&nbsp; &nbsp; &nbsp; &nbsp; 'type'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; => 'checkbox',&nbsp; &nbsp; &nbsp; &nbsp; 'label'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;=> __('Subscribe to our Newsletter.'),&nbsp; &nbsp; &nbsp; &nbsp; 'required'&nbsp; => false,&nbsp; &nbsp; &nbsp; &nbsp; 'default' => 1&nbsp;&nbsp; &nbsp; ),&nbsp; $checkout->get_value( 'sendy_woocommerce_agree' ));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}add_filter( 'woocommerce_after_checkout_billing_form' , 'add_field_sendy_woocommerce_agree', 10, 1 );// Savefunction action_woocommerce_checkout_create_order( $order, $data ) {&nbsp; &nbsp; if ( isset($_POST['sendy_woocommerce_agree']) && ! empty($_POST['sendy_woocommerce_agree']) ) {&nbsp; &nbsp; &nbsp; &nbsp; $order->update_meta_data( 'sendy_woocommerce_agree', sanitize_text_field( $_POST['sendy_woocommerce_agree'] ) );&nbsp; &nbsp; }&nbsp;}add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );// Display the custom field value on admin order pages after billing adress:function action_woocommerce_admin_order_data_after_billing_address( $order ) {&nbsp; &nbsp; echo '<p><strong>'.__('Sendy').':</strong> ' . $order->get_meta('sendy_woocommerce_agree') . '</p>';&nbsp;}add_action( 'woocommerce_admin_order_data_after_billing_address', 'action_woocommerce_admin_order_data_after_billing_address', 10, 1 );
打开App,查看更多内容
随时随地看视频慕课网APP