fbpx

Category: WooCommerce

WooCommerce has lots of shortcodes but it doesn't have one to display pricing.

The code below will render the product price that's currently loaded OR if you pass the ID of a specific product.

<?php

add_shortcode( 'orb_wc_product_price', 'orb_custom_shortcode_wc_product_price' );

/**
 * Shortcode to display WooCommerce Product Price
 * [orb_wc_product_price]
 * Modified by Orbisius to auto-detect product ID if not passed.
 * Original code by Aashik P – a11n (@aashik) posted on WP org forums
 * @see https://wordpress.org/support/topic/product-price-shortcode/
 */
function orb_custom_shortcode_wc_product_price( $atts ) {
    if (!function_exists('wc_get_product') || !function_exists('get_queried_object_id')) {
        return '';
    }

    $atts = shortcode_atts( array(
        'id' => null
    ), $atts, 'orb_wc_product_price' );

    if (empty($atts['id'])) {
        $atts['id'] = get_queried_object_id();
    }

    if ( empty( $atts[ 'id' ] ) ) {
        return '';
    }

    $product = wc_get_product( $atts['id'] );

    if ( ! $product ) {
        return '';
    }

    $price = $product->get_price();
    $price_fmt = wc_price($price);
    $price_html = $price_fmt;

    // sometimes it shows an incorrect value
    // $price_html = return $product->get_price_html();

    return $price_html;
}

usage:

[orb_wc_product_price] or [orb_wc_product_price id=123]

Installation

To use this code it's highly recommended that you create a system plugin.

This is a plugin that's created in /wp-content/mu-plugins/ folder. It is automatically active.

If you use a WordPress child theme you can paste the code in the functions.php.

Skip the <?php of the code if you're appended to an existing php file.

Join our mailing list

Get important news about cool products we release and invitations to beta test new products

Find out the Social networks we're on