19

i make one shortcode for get product title, image and price. i am getting all title, link and image properly but not getting price. but problem is

add_shortcode('product_data','custom_product_function');
function custom_product_function($atts)
{
    $post_id = $atts['id'];
    $title = get_the_title($post_id);
    $link = get_the_permalink($post_id);
    $price = get_the_price($post_id);
    $image = get_the_post_thumbnail($post_id, 'thumbnail');
    $data ='<div class="releated-products wow fadeInUp"><a href="'.$link.'">'.$image.'<h5>'.$title.'</h5><h6>'.$price.'</h6></a></div>';
    return $data;
}

$price = get_the_price($post_id); i guess this function not correct

any idea how to get price now.

Thanks you

1 Answer 1

49

You can create a product object using the following function:

$product = wc_get_product( $post_id );

And after that you will be able to access to all product's data. All available methods can be found here, but the ones you need are:

$product->get_regular_price();
$product->get_sale_price();
$product->get_price();
4
  • thanks for reply. i look that already. checking again. but for that i need to change my shortcode function different way. am i right ? is there anyway to do inside my shortcode
    – Accore LTD
    Commented Mar 8, 2018 at 10:52
  • 1
    Just add $product = wc_get_product( $post_id ); somewhere above $price and set $price = $product->get_price(). Commented Mar 8, 2018 at 12:07
  • 2
    This crashed my local Commented Aug 23, 2018 at 12:33
  • 1
    WC_Product class and methods link correction: woocommerce.github.io/code-reference/classes/WC-Product.html
    – stemon
    Commented Feb 18, 2022 at 17:51

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