skip to Main Content

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


  1. Chosen as BEST ANSWER

    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


  2. Use instead wc_get_products() function to query your products and you will get directly an array of WC_Product Objects where you will be able to use the WC_Product method get_name() like:

    // Get all published products
    $products = wc_get_products( array(
        'limit' => -1,
        'status' => 'publish',
    ) );
    
    $product_count = count($products); // Get the product count
    echo '<p>Count: '. $product_count .'</p>'; // Output
    
    // Loop through the array of product objects
    foreach ( $products as $product ) {
        $product_name = $product->get_name(); // Get product name
        echo '<p>'. $product_name .'</p>'; // Output
    }
    

    It should better work.

    Note: There is no need to declare anything.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search