Capture custom checkout field value in Woocommerce

拟墨画扇 提交于 2019-12-08 18:16:28

Updated

There are some mistakes and missing things in your code. Try the following instead:

// Display a custom checkout field
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
    echo '<div id="my_custom_checkout_field"><h2>' . __('My Field') . '</h2>';

    woocommerce_form_field( '_custom_field', array(
        'type'          => 'text',
        'class'         => array('my-custom-field form-row-wide'),
        'label'         => __('Fill in this field'),
        'placeholder'   => __('Enter something'),
        ), $checkout->get_value( '_custom_field' ));

    echo '</div>';
}

// Save the custom checkout field in the order meta
add_action( 'woocommerce_checkout_create_order', 'save_order_custom_meta_data', 10, 2 );
function save_order_custom_meta_data( $order, $data ) {
    if ( isset($_POST['_custom_field']) )
        $order->update_meta_data('_custom_field', sanitize_text_field( $_POST['_custom_field'] ) );
}


add_action( 'woocommerce_order_status_completed', 'action_on_order_status_completed', 10, 2 ); 
function action_on_order_status_completed( $order_id, $order ) { 
    // The order data (array)
    $data = array(
        'email'         => $order->get_billing_email(),
        'first_name'    => $order->get_billing_first_name(),
        'last_name'     => $order->get_billing_last_name(),
        'phone'         => $order->get_billing_phone()(),
        'address'       => $order->get_billing_address_1(),
        'city'          => $order->get_billing_city(),
        'province'      => $order->get_billing_state(),
        'country'       => $order->get_billing_country(),
        'order'         => $order->get_order_number()
    );

    // Get the custom field value (and add it if not empty)
    if( $custom_field = $order->get_meta('_custom_field') ) {
        // Add it to the array
        $data['custom_field'] = $custom_field;
    }

    //Encode the array into JSON.
    $json_data = json_encode( $data ); 

    // The Url
    $url = 'localhost/wp/recolector.php';

    //Initiate cURL.
    $ch = curl_init($url);

    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);

    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

    //Execute the request
    $result = curl_exec($ch);

    // Set the return result in the order as custom meta data (if needed)
    $order->update_meta_data('_curl_result', $result );
    $order->save();
}

It should better work now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!