【问题标题】:Unable to save custom checkbox value from WooCommerce checkout [duplicate]无法从 WooCommerce 结帐中保存自定义复选框值 [重复]
【发布时间】:2020-09-02 02:52:31
【问题描述】:

我创建了在结算表单后将复选框添加到 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' );访问它

我做错了什么?

【问题讨论】:

  • @LoicTheAztec 抱歉重复,老实说,我没有在网站上或谷歌上找到与我相关的搜索词的其他答案,答案确实是我正在寻找的,但问题是有问题的重复 :)
  • 没问题别着急,有的时候很难找到现有的相关答案……下面的答案就好了,就是有点不一样。

标签: php wordpress woocommerce checkout hook-woocommerce


【解决方案1】:

按以下方式试试

function add_field_sendy_woocommerce_agree( $checkout ) {

    woocommerce_form_field( 'sendy_woocommerce_agree', array(
        'type'          => 'checkbox',
        'label'         => __('Subscribe to our Newsletter.'),
        'required'  => false,
        'default' => 1 
    ),  $checkout->get_value( 'sendy_woocommerce_agree' ));                               
}
add_filter( 'woocommerce_after_checkout_billing_form' , 'add_field_sendy_woocommerce_agree', 10, 1 );

// Save
function action_woocommerce_checkout_create_order( $order, $data ) {
    if ( isset($_POST['sendy_woocommerce_agree']) && ! empty($_POST['sendy_woocommerce_agree']) ) {
        $order->update_meta_data( 'sendy_woocommerce_agree', sanitize_text_field( $_POST['sendy_woocommerce_agree'] ) );
    } 
}
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 ) {
    echo '<p><strong>'.__('Sendy').':</strong> ' . $order->get_meta('sendy_woocommerce_agree') . '</p>'; 
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'action_woocommerce_admin_order_data_after_billing_address', 10, 1 );

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 2019-11-02
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2020-07-15
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多