Get woocommerce product price by id [closed]

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

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();

Leave a Comment