1

I have created a simple plugin that imports products from my CSV file, which works fine. The function for creating new products looks like this (simplified):

function create_products() {

    foreach($keys as $key) {

        // Assign variables
        // ...

        // Create new product
        $objProduct = new WC_Product();

        $objProduct->set_name($title);
        $objProduct->set_status("publish");
        $objProduct->set_catalog_visibility('visible');
        $objProduct->set_price($price);
        $objProduct->set_regular_price($price);
        $objProduct->set_manage_stock(true);
        $objProduct->set_stock_quantity($stock);
        $objProduct->set_stock_status('instock');
        $objProduct->set_backorders('notify');
        $objProduct->set_reviews_allowed(true);
        $objProduct->set_sold_individually(false);
        $objProduct->set_sku($sku);

        // Save it
        $product_id = $objProduct->save();

    }
}

It works well. After that I have another function that just updates the title, price, SKU and stock quantity of products that already exist. It looks like this (again, simplified):

function update_products() {

    foreach($keys as $key) {

        // Get product ID and it's object
        // $id, $objProduct

        // Assign variables
        // $title, $stock, $price, $sku

        // Perform updates
        update_stock($id, $stock); // updates '_stock' and '_stock_status' meta, runs wp_update_product_stock() method
        update_post_meta($id, '_regular_price', (float)$price);
        $objProduct->set_sku($sku);
        $objProduct->set_name($title);
        $objProduct->save();
    }
}

But it doesn't work at all. Somehow, the SKU (updated with set_sku()) and stock updating works. It gets updated, but the rest (name and price) does not. As for the title, I have also tried wp_update_post() method, and tried to change the 'post_title', but no results either.

All of them are simple products. How can I update their titles, prices and stock values?

Kristián Filo
  • 827
  • 2
  • 8
  • 25

1 Answers1

1

Try code below. I checked it's work fine.

function update_products() {

    foreach($keys as $key) {

        // Get product ID and it's object
        // $id, $objProduct

        // Assign variables
        // $title, $stock, $price, $sku

        // Perform updates
        // Create new product
        $objProduct = wc_get_product($id);
        if ( $objProduct instanceof WC_Product) {
            $objProduct->set_name($title);
            $objProduct->set_regular_price($price);
            $objProduct->set_sku($sku);
            $objProduct->set_stock_quantity($stock);

            // Save it
            $objProduct->save();
        }
    }
}

Hope help you. Check if product exist.

Dmitry Leiko
  • 3,970
  • 3
  • 25
  • 42