questions

Display in WooCommerce thankyou a custom field value based on a custom table

Rate this post

I have a code i have done to display custom field value on thank you page but it does not display the value. However i am able to display the value on the backend admin page. Below is my code:

add_action( 'woocommerce_thankyou_order_received_text', 'additionalnote_order_data_in_admin', 10, 1    );
function additionalnote_order_data_in_admin($order){
    global $wpdb;
    global $post_id;
    
    $order = new WC_Order( $post_id );

    $table_name = $wpdb->prefix . 'woocommerce_custom_fields';

    $result = $wpdb->get_results("SELECT * FROM $table_name ");

    if(!empty($result)){

        foreach($result as $query){
            $name = $query->name;
            $label = $query->label;
            $get_order = $order->get_meta('_'.$name);

            echo '<p><strong>'.__('Delivery Date').':</strong> ' . $get_order . '</p>';
        }
    }
}

 

✔️Solution:

There are some mistakes in your code… Use the following instead:

add_action( 'woocommerce_thankyou_order_received_text', 'additional_note_order_data_in_admin', 10, 1    );
function additional_note_order_data_in_admin( $order_received_text, $order ){
    global $wpdb;

    $order_id = $order->get_id(); // Get order Id (For info, If needed)

    $results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}woocommerce_custom_fields");

    if ( ! empty($results) ) {
        foreach ( $results as $result ) {
            if ( $meta_value = $order->get_meta( '_'.$result->name ) ) {
                $order_received_text .= '</p><p><strong>' . __('Delivery Date') . ':</strong> ' . $meta_value;
            }
        }
    }
    return $order_received_text;
}

Code goes in functions.php file of the active child theme (or active theme). It should better work.

Leave a Reply

Your email address will not be published.

Back to top button