2
votes

I cannot get the order ID in a custom woocommerce email template by shortcode. It does work directly.

Working code in admin-new-order.php template:

echo $order->get_id();

My shortcode below does not work and I don't know why. My goal is to eventually insert text variables like "Hello Firstname" by shortcode into the email template.

function custom_first_name($order, $order_id){
global $woocommerce, $post;
global $order_id, $order;
$order = new WC_Order( $order_id );
return $order->get_id();
}
add_shortcode( 'custom-woocommerce-name' , 'custom_first_name' );

I add the shortcode to the in admin-new-order.php template via this code:

echo do_shortcode('[custom-woocommerce-name]');

$order->get_id() and the shortcode should both be outputting the order id.

1

1 Answers

2
votes

To get the Order Id from a shortcode used in admin-new-order.php template, you will have to use the following function code instead:

function wc_custom_first_name( $atts ){
    // Extract shortcode attributes
    extract( shortcode_atts( array(
        'id' => '',
    ), $atts, 'wc-custom-name' ) );

    return $id; // return order id
}
add_shortcode( 'wc-custom-name' , 'wc_custom_first_name' );

Code goes in functions.php file of the active child theme (or active theme).

Then you will use the following in admin-new-order.php template file:

echo do_shortcode("[wc-custom-name id='{$order->get_id()}']");

Tested and works.

Note:

The available arguments variables passed to admin-new-order.php template are:

  • $order
  • $email_heading
  • $additional_content
  • $sent_to_admin
  • $plain_text
  • $email