从 WooCommerce 中的短代码保存自定义结帐字段

问题描述 投票:0回答:1

使用 WooCommerce,我在将自定义字段的值保存到数据库时遇到一些问题。我遵循了几个指南,但由于某种原因它对我不起作用。

这是我添加到函数 PHP 文件中的代码:

// Print out checkbox on checkout
add_shortcode( 'replacement_item', 'custom_woocommerce_form_shortcode' );
function custom_woocommerce_form_shortcode() {
    ob_start(); // Start output buffering
    
    // Output the form field using woocommerce_form_field function
    woocommerce_form_field( 'replacement_checkbox', array(
        'type'      => 'checkbox',
        'default'   => true,
        'class'     => array('input-checkbox'),
        'label'     => __('Allow substitute items for all products.'),
    ),  WC()->checkout->get_value( 'replacement_checkbox' ) );

    // Get the buffered content and return it
    $output = ob_get_clean();
    return $output;
}

// save value from checkbox above to database --
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta', 10, 1 );
function custom_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['replacement_checkbox'] ) )
        update_post_meta( $order_id, 'replacement_checkbox', $_POST['replacement_checkbox'] );
}
php woocommerce field checkout shortcode
1个回答
0
投票

假设您的自定义复选框显示在结帐表单内,请尝试以下操作:

// Print out checkbox on checkout
add_shortcode( 'replacement_item', 'custom_woocommerce_form_shortcode' );
function custom_woocommerce_form_shortcode() {
    ob_start(); // Start buffering output
    
    // Output the form field using woocommerce_form_field function
    woocommerce_form_field( 'replacement_checkbox', array(
        'type'      => 'checkbox',
        'default'   => true,
        'class'     => array('input-checkbox'),
        'label'     => __('Allow substitute items for all products.'),
    ),  WC()->checkout->get_value( 'replacement_checkbox' ) );

    // Return the buffered content
    return ob_get_clean();
}

// Save checkbox value as order metadata
add_action( 'woocommerce_checkout_create_order', 'save_custom_checkout_checkbox_field'  );
function save_custom_checkout_checkbox_field( $order ) {
    $order->update_meta_data('replacement_checkbox', isset($_POST['replacement_checkbox']) ? '1' : '0' );
}
© www.soinside.com 2019 - 2024. All rights reserved.