How to create a shortcode to display a product SKU in WooCommerce

WooCommerce allows you to extend its functionality using shortcodes—small pieces of code that you can insert into pages, posts, or widgets to display dynamic information. In this article, we will create a custom shortcode that displays a product’s SKU based on its ID. If no ID is specified, the shortcode will use the global product. Additionally, we’ll add a second parameter to define a default value in case the product has no SKU.

 

Creating the shortcode

To add the shortcode to your WooCommerce store, insert the following code into your child theme’s functions.php file or a custom plugin:

>?php
function letsgodev_get_sku( $atts ) {
    $atts = shortcode_atts( [
        'id'      => '',
        'default' => 'SKU not available'
    ], $atts );

    $product = null;

    if ( ! empty( $atts['id'] ) ) {
        $product = wc_get_product( $atts['id'] );
    } elseif ( is_singular( 'product' ) && function_exists( 'wc_get_product' ) ) {
        global $product;
    }

    if ( ! $product ) {
        return 'Product not found';
    }

    $sku = $product->get_sku();

    return $sku ? esc_html( $sku ) : esc_html( $atts['default'] );
}

add_shortcode( 'letsgodev_get_sku', 'letsgodev_get_sku' );

 

How to use the shortcode

Once the code is added, you can use the shortcode anywhere on your site:

  • To display the SKU of a specific product, use:
    [letsgodev_get_sku id="123"]

    (where 123 is the product ID).

 

  • To show an alternative message if the SKU is not defined, use the default parameter:
    [letsgodev_get_sku id="123" default="No code available"]

    If the product has no SKU, it will display “No code available.

 

  • To display the SKU of the current product on a single product page, simply use:
    [letsgodev_get_sku]

    (this will use the global product if you’re on a product page).

Other product properties

This same approach can be used to display other product properties in WooCommerce, such as:

  • Stock quantity$product->get_stock_quantity();
  • Price: $product->get_price();
  • Short description$product->get_short_description();
  • Category$product->get_categories();

Simply modify the function to fetch and return the information you need.

We hope this guide was helpful! If you have any questions or want more shortcode examples for WooCommerce, leave us a comment.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x