phpwordpresswoocommerceproductshortcode

Shortcode displaying the product name and price in WooCommerce product page


I need to show product title and current price via shortcode in the product page without using product id.

I mean my code with automatically detect product id from current product page where i use shortcode and get the title and price.

For example this one, I have to use the specific id inside shortcode like this [iw_product_price id=''] to show product price.

// Get WooCommerce product price by ID via shortcode: [iw_product_price id='']
function iw_product_price_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
        $_product = wc_get_product( $atts['id'] );
        $html = $_product->get_price_html();
    }
    return $html;
}
add_shortcode( 'iw_product_price', 'iw_product_price_shortcode' );

// Get WooCommerce product name by ID via shortcode: [iw_product_name id='']
function iw_product_name_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
        $_product = wc_get_product( $atts['id'] );
        $html = $_product->get_title();
    }
    return $html; 
} 
add_shortcode( 'iw_product_name', 'iw_product_name_shortcode' );

Solution

  • The following shortcode will detect the product ID (or the product Object) and will display the product name with the formatted product price in WooCommerce product pages:

    add_shortcode( 'product_name_price', 'get_product_name_price_shortcode' );
    function get_product_name_price_shortcode( $atts ) {
        // Extract shortcode attributes
        extract( shortcode_atts( array(
            'id' => get_the_ID(),
        ), $atts, 'product_name_price' ) );
        
        global $product;
    
        $is_a_product =  is_a($product, 'WC_Product');
        
        if( ! $is_a_product  && 'product' ===  get_post_type( $id )  ){
            $product = wc_get_product( $id ); // get the product object from the ID
        } 
        if ( $is_a_product ) {
            return '<span class="product-name">' . $product->get_name() . '</span> <br>' .
            $product->get_price_html();
        }
    }
    

    Usage as a simple shortcode: [product_name_price]

    Usage as a shortcode using the product ID argument: [product_name_price id='28']