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.

6 Responses

  1. Cuando buscas multiservicios para reformas en tu hogar, es crucial elegir una opción confiable. Muchas compañías ofrecen servicios integrales que incluyen desde servicios de limpieza hasta reparaciones a domicilio. Si necesitas ayuda, te recomiendo consultar reparaciones del hogar para encontrar opciones que se adapten a tus necesidades. Además, siempre es útil leer reseñas y comparar presupuestos antes de tomar una decisión final.

  2. 1xBet yükləmək istəyənlər üçün ən asan üsul 1xbet yükle android seçimidir. Mən özüm də bu yolu seçdim və hər şey rahat başa düşülən idi. Bu proses üçün yalnız 1xbet yukle etmək kifayətdir. Mənim də məhz bu bənddə 1xbet mobil yükle https://1xbet-app1-android-ehj.com araşdırdım və həqiqətən də çox faydalı məlumatlar tapdım. Bundan əlavə 1xbet yükləndikdən sonra və onu işə saldıqda interfeysi çox istifadəçi dostu idi. Bu üsul xüsusilə mobil oyun həvəskarları üçün ideal seçimdir.

  3. I recently wanted to try out 1xbet and started looking for the best way to download it. The process turned out to be pretty straightforward once I figured out the right steps. For those who prefer mobile access, the 1xbet download mobile option is super convenient. I also came across the 1xbet apk download method, which worked seamlessly on my Android device. If you’re searching for a reliable way to access the platform, I found that using the official 1xbet application ensures you get the latest updates and features. By the way, I was looking into 1xbet apk download https://1xbet-apk-android1.com/ and noticed that it covered all the essential details for a smooth setup. Overall, whether you’re downloading via the app store or directly from the site, the process is quick and hassle-free.

  4. Слышал про игру Aviator от 1xBet и решил попробовать. Достаточно интересный и динамичный игровой процесс. Мне импонирует возможность самостоятельно регулировать уровень риска. Рекомендую сначала попробовать на небольших суммах, чтобы вникнуть в правила. Недавно искал aviator https://aviator-nop.com и нашёл несколько полезных материалов. Теперь играю с большим пониманием и удовольствием. Чтобы добиться успеха, важно сначала разобраться в стратегиях и тактиках. Удачи в игре и больших выигрышей!

  5. If you’re looking to jump into the world of online betting, downloading the 1xbet application is a great first step. The process is straightforward, whether you’re using your mobile phone. You can find the 1xbet apk download quickly on their official site or even through the Play Store. I recently searched for 1xbet apk download and was impressed by how smoothly the mobile version runs. The 1xbet mobile download ensures you can place bets on the go without any hassle. For those who prefer direct downloads, the 1xbet apk download for Android is also a reliable option. Overall, the 1xbet application offers a user-friendly experience, making it a top choice for experienced bettors.

  6. I’ve been using the 1xbet app for a while now, and it’s been a great experience overall. The 1xbet yükle app download was straightforward, and it works perfectly on my iPhone. If you’re looking for a reliable betting app, I definitely recommend checking out 1xbet yükle app download — it’s user-friendly and packed with features. The 1xbet iphone version is particularly impressive, with quick loading times and a sleek interface. Whether you’re into sports or casino games, the 1xbet yukle ios option is worth considering. It’s become my go-to app for placing bets on the go.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top