Using wc_get_product() with a PHP variable for product ID

Update related to your recent comment. The 2 ways to explore:

1) Instead of you should try to use to get the product object (avoiding the error):

$courseID = the_field('course_id');

// Optionally try this (uncommenting)
// $courseID = (int)$courseID;

// Get an instance of the product object
$_product = new WC_Product($courseID);

2) Alternatively if this doesn't work, you should try to use get_post_meta() function to get the product price (or any product meta data) this way:

<?php 
//Gets the course ID from the custom field entered by user
$courseID = the_field('course_id');

// Get the product price (from this course ID):
$course_price = get_post_meta($courseID, '_regular_price', true); 

// Output the Course price
?>  <span class="coursePrice">$<?php echo $course_price;?></span>

This time you should get displayed the price with one or the other solutions.


Update: May be Also you need to convert $courseID to an integer variable.

Because you need to use your variable $courseID inside wc_get_product() (without the 2 ') function this way:

<?php 

//Gets the course ID from the custom field entered by user
$courseID = the_field('course_id');

// Optionally try this (uncommenting)
// $courseID = (int)$courseID;

// Here
$_product = wc_get_product( $courseID );

$course_price = $_product->get_regular_price();

// Output the Course price
?>  <span class="coursePrice">$<?php echo $course_price;?></span>

This should work now.


You can try this out :

$courseID = the_field('course_id');
$product = get_product( $courseID );