I'm new to PHP. I want to create a shortcode that outputs a user's order number, but I'm having trouble.

All I know is that the order ID variable is "$order->get_id();"

  • You need to provide a lot more context. Using a variable is nothing special or unusual. If the variable is available, just use it. The problem is, what is the variable, and when it is available. $order doesn't just exist, you have to get it from somewhere. In the case of WooCommerce, users can have many orders, so what order are you using? How are you getting it? Where is the shortcode going to be used? Aug 19, 2019 at 12:27

1 Answer 1


Would need to know how you are planning to use this shortcode because doing what you are asking raises the issue of what you want the shortcode to do if the user has multiple orders?

If this shortcode is going to be displayed on a page or post that is specific to a specific order then the shortcode can be created as follows:

The following two functions should be in your themes functions.php file or in your plugins main php file.

This registers your shortcode:

function register_my_shortcode() {
add_shortcode( 'get_current_order_number', 'get_current_order_number_callback' ) );
add_action( 'init', 'register_my_shortcode', 10 );

This is the function callback that builds what you want to do with your shortcode:

function get_current_order_number_callback( $atts ) {
// This is where you can get your order number.
global $post;
$order = new WC_Order($post->ID);
$output = '';

// Good to do a check that the order number is not empty.
if ( ! empty( $order->get_order_number() ) ) :
// This is where you can declare attributes that you can add in your shortcode.
$atts = shortcode_atts( array(
        'id' => 'default-id',
        'container_class' => 'default-container-class',
        'class' => 'default-class',
    ), $atts );

// Now you can build the elements that you want to display the order number in.
$output .= '<div class="' . $atts['container_class'] . '">;
$output .= '<span id="' . $atts['id'] . '" class="' . $atts['class'] . '">' . $order->get_order_number() . '</span>';
$output .= '</div>';

// If order number is not empty will return your shortcode build above.
return $output;


// If order number is empty will return false.
return false;

Your shortcode will look like this and with no atts will use your defaults:


or with atts added:

[get_current_order_number id="43" container_class="custom-container" class="order-number-text"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.