结帐时从 woocommerce 自定义字段导出数据

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

我在结帐(选择列表)中添加了一个自定义字段,我想将该字段与所有其他字段一起导入,但它在我正在使用的任何插件上根本不显示自定义字段。

知道我需要做什么才能导出该字段吗?

谢谢。

这是我添加到我的functions.php 文件中的代码。


//* Add select field to the checkout page
add_action('woocommerce_before_order_notes', 'wps_add_select_checkout_field');

function wps_add_select_checkout_field( $checkout ) {

    woocommerce_form_field( 'studio', array(
        'type'          => 'select',
        'class'         => array( 'wps-drop' ),
        'label'         => __( 'Select your studio' ),
        'required'    => true,
        'priority'    => 5, // Priority sorting option
        'options'       => array(
            'blank'     => __( 'Select Your Studio', 'wps' ),
           'Ukraine & Poland' => __('Ukraine & Poland', 'wps' ),
            'Israel' => __('Israel',  'wps' ),
           'Kyiv' => __('Kyiv',  'wps' ),
            'Finland ' => __('Finland',  'wps' )
        )
 ),
    $checkout->get_value( 'studio' ));
}



//* Process the checkout
 add_action('woocommerce_checkout_process', 'wps_select_checkout_field_process');
 function wps_select_checkout_field_process() {
    global $woocommerce;

    // Check if set, if its not set add an error.
    if ($_POST['studio'] == "blank")
     wc_add_notice( '<strong>Please select your studio</strong>', 'error' );
 }

知道我需要做什么才能导出该字段吗?

谢谢。

woocommerce export field
1个回答
0
投票

您的代码没问题,但您没有保存该字段!

添加此字段以保存订单元数据中的字段:

/**
 * Saves the value of the "studio" custom checkout field to the order meta data.
 *
 * @param int $order_id The ID of the order being processed.
 */
function wps_save_select_checkout_field( $order_id ) {
    // Check if the "studio" field was submitted and is not empty.
    if ( ! empty( $_POST['studio'] ) ) {
        // Sanitize the input before saving it to the database.
        $studio_value = sanitize_text_field( $_POST['studio'] );

        // Update the order meta data.
        update_post_meta( $order_id, 'studio', $studio_value );
    }
}

add_action( 'woocommerce_checkout_update_order_meta', 'wps_save_select_checkout_field' );

然后您可以像任何其他元字段一样检索它。这是一个函数,它将输出在“studio”字段中所做的选择:

/**
 * Gets the value of the "studio" custom checkout field from a WooCommerce order.
 *
 * @param int $order_id The ID of the WooCommerce order.
 * @return string|null The value of the "studio" field, or null if not found.
 */
function wps_get_order_studio_field( $order_id ) {
    $order = wc_get_order( $order_id );

    if ( $order ) {
        return $order->get_meta( 'studio' );
    }
    
    return null;
    
}

用途:

// save the choice in a variable for order with id 1235
$studio_selection = wps_get_order_studio_field( '1235 );

// display the choice
echo esc_html( $studio_selection );

注意:我强烈建议不要使用“studio”作为字段名称,添加前缀以避免冲突,即“wps_studio”

© www.soinside.com 2019 - 2024. All rights reserved.