Add customer email in a text on WooCommerce Order

2020-07-22 17:39发布

问题:

In WooCommerce, on top of my thank you / order-received page, I've added a custom text, with the following code:

add_action( 'woocommerce_thankyou', 'my_order_received_text', 1, 0);
function my_order_received_text(){

    echo '<div class="my_thankyou2"><p>' . __('Your download link was sent to: ') . '</p></div>' ;

}

How can I get the email address of the customer added to the end of the custom text?

回答1:

To get the customer billing email, you can use one of those:

  • The Woocommerce WC_Order method get_billing_email()
  • The WordPress function get_post_meta() with the meta key _billing_email from order ID.

Now you can set the text in 2 different locations:

1) On top of Order received page:

add_filter( 'woocommerce_thankyou_order_received_text', 'my_order_received_text', 10, 2 );
function my_order_received_text( $text, $order ){
    if( ! is_a($order, 'WC_Order') ) {
        return $text;
    }
    // Get Customer billing email
    $email = $order->get_billing_email();

    return $text . '<br>
    <div class="my_thankyou2"><p>' . __('Your download link was sent to: ') . $email . '</p></div>' ;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


2) On bottom of Order received page:

Using the WC_Order method get_billing_email() this way:

add_action( 'woocommerce_thankyou', 'my_order_received_text', 10, 1 );
function my_order_received_text( $order_id ){
    if( ! $order_id ){
        return;
    }
    $order = wc_get_order( $order_id ); // Get an instance of the WC_Order Object
    $email = $order->get_billing_email(); // Get Customer billing email

    echo '<div class="my_thankyou2"><p>' . __('Your download link was sent to: ') . $email . '</p></div>' ;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


Alternatively, using WordPress get_post_meta() function, replacing in the function:

$order = wc_get_order( $order_id ); // Get an instance of the WC_Order Object
$email = $order->get_billing_email(); // Get Customer billing email

By the following line:

$email = get_post_meta( $order_id, '_billing_email', true ); // Get Customer billing email