在 Woocommerce 订单页面中,创建与订单 ID 相关的自定义文本字段

我需要自定义 url 必须不同,与订单 ID 相关(例如 100 个订单,100 个不同的自定义 url,每个订单页面一个)。

// Display user custom field

add_action( 'woocommerce_order_details_before_order_table', 'add_user_custom_url_field_to_order' );

function add_user_custom_url_field_to_order( $order ) {

    global $current_user;


    $custom_url = get_user_meta( $current_user->ID, 'custom_URL', true );

    ?>

    <form method="post">

         <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">

            <label for="custom_URL"><?php _e( 'URL', 'woocommerce' ); ?></label>

            <input type="text" name="custom_URL" id="custom_URL" value="<?php echo $custom_url; ?>" />

        </p>

        <input type="submit" name="submit-custom_URL" value="<?php _e('RUN', 'woocommerce'); ?>" /><br/>

    </form>

    <?php

}


// Save the field as custom user data

add_action( 'template_redirect', 'save_user_custom_url_field_from_order' );

function save_user_custom_url_field_from_order() {

    global $current_user;


    if( isset($_POST['custom_URL']) && ! empty($_POST['custom_URL']) ){

        update_user_meta( $current_user->ID, 'custom_URL', sanitize_url( $_POST['custom_URL'] ) );

        wc_add_notice( __("Your custom URL has been saved saved", "woocommerce") );

    }

}


繁星淼淼
浏览 186回答 1
1回答

桃花长相依

以下是将数据保存为订单自定义元数据而不是用户元数据的方法:add_action( 'woocommerce_order_details_before_order_table', 'add_custom_url_field_to_order' );function add_custom_url_field_to_order( $order ) {&nbsp; &nbsp; $custom_url = $order->get_meta( 'custom_URL' );&nbsp; &nbsp; ?>&nbsp; &nbsp; <form method="post">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label for="custom_URL"><?php _e( 'URL', 'woocommerce' ); ?></label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" name="custom_URL" id="custom_URL" value="<?php echo $custom_url; ?>" />&nbsp; &nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; &nbsp; &nbsp; <input type="hidden" name="the_order_id" value="<?php echo $order->get_id(); ?>" />&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" name="submit-custom_URL" value="<?php _e('RUN', 'woocommerce'); ?>" /><br/>&nbsp; &nbsp; </form>&nbsp; &nbsp; <?php}// Save the fieldadd_action( 'template_redirect', 'save_custom_url_field_from_order' );function save_custom_url_field_from_order() {&nbsp; &nbsp; if( isset($_POST['custom_URL']) && ! empty($_POST['custom_URL']) && isset($_POST['the_order_id']) ){&nbsp; &nbsp; &nbsp; &nbsp; update_post_meta( esc_attr($_POST['the_order_id']), 'custom_URL', sanitize_url( $_POST['custom_URL'] ) );&nbsp; &nbsp; &nbsp; &nbsp; wc_add_notice( __("Submitted data has been saved", "woocommerce") );&nbsp; &nbsp; }}代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。现在,每个自定义 URL 将与订单相关,但不再与用户元数据相关。
打开App,查看更多内容
随时随地看视频慕课网APP