I would be so greatful for any assistance as this is driving me mad. After many hours of troubleshooting, I have narrowed the issue but have no idea why it occurs…
My code iterates through all the products within the woocommmerce store and create an order with a relevant product for a customer. It has stopped working when I updated.
The error log displays
PHP Fatal error: Uncaught Error: Call to a member function get_name()
my code [in its simplest] to diagnose the issue:
//declarations
global $wpdb;
global $woocommerce;
//get all product (ids) on system
$all_ids = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
'fields' => 'ids',
) );
//create an array of the product ids found
$counterOfProducts=0;
foreach ( $all_ids as $id ) {
$arrayOfProdIds[] = $id;
$counterOfProducts=$counterOfProducts+1;
}
foreach ($arrayOfProdIds as $IdOfproductFromArray) {
echo '<p>array id value:: '.$IdOfproductFromArray.'</p>';
//$product = wc_get_product( $IdOfRoductFromArray );
$product = wc_get_product( 30302 ); // this is a test id that I know to exist
$theTestproductName = $product->get_name();
echo $theTestproductName;
}
The exception is thrown when get_name is used but the above product is a product that I know exists.
All help is really appreciated.
2
Answers
as per LoicTheAztec, my answer worked but was not the correct way to resolve this issue so I have removed in case it gives an issue to someone else
Use instead
wc_get_products()
function to query your products and you will get directly an array ofWC_Product
Objects where you will be able to use theWC_Product
methodget_name()
like:It should better work.
Note: There is no need to declare anything.