Using wc_get_product () with a PHP variable for product id

I create custom landing pages for products in WooCommerce, and I would like to get the price of the product, by the way, to display them on the landing page.

Each landing page has several custom fields that allow the WP administrator to add content for the landing page, as well as the product identifier, which will then be used to formulate the product price, URL for verification, etc.

I cannot get it to wc_get_product();work with my custom field or with a modified variable. It only works when I use the direct identifier. I think there is something that I donโ€™t understand about how variables work in PHP. Here is my code.

<?php 

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

// This line is where the problem is...
$_product = wc_get_product('$courseID');

// If I replace the line above with this line
// $_product = wc_get_product('7217');
//  everything works great, but that does not let 
// each landing page function based on the custom fields where the user determines 
// the product ID they are selling on that landing page.


// Get the price of the product
$course_price = $_product->get_regular_price();

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

Refresh

, wc_get_product( $courseID ); get_product( $courseID );:

Fatal error: Call to a member function get_regular_price() on a non-object in ... 
+4
4

, @LoicTheAztec . , , - .

Advanced Custom Fields , ACF the_field() . , ( , php-). , ACf get_field(), , .

$courseID .

$courseID = get_field('course_id'); 

. , @LoicTheAztec .

+1

, . 2 :

1) , ( ):

$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) , get_post_meta() ( ) :

<?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>

.


: , $courseID .

$courseID wc_get_product() ( 2 '):

<?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>

.

+4

:

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

$_product = wc_get_product( id );

API-: wc_get_product

0

Source: https://habr.com/ru/post/1667186/


All Articles