Using Product CRUD setter methods in Woocommerce 3

In the code bellow, I can't set some product category and product tags:

The code is located in my functions.php file:

<?php

$product = new WC_Product;
$product->set_name("product");
$product->set_regular_price('150');
$set_cat = $product->set_category_ids( array(17) );
$set_tag = $product->set_tag_ids( [18, 19] );
$product->save();

var_dump($set_cat);//NULL
var_dump($set_tag);//NULL

The product is created with the correct name and price. But I get nothing for the product category and product tags:

terms:
[terms table][1]

term_taxonomy:
[term_taxonomy table][2]

Edit: I have moved this code in index.php file and It works.

Upvotes: 1

Views: 1106

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253919

Since Woocommerce 3, new CRUD methods are available.

But you can not use a setter method in a variables like in this extract of your code:

$set_cat = $product->set_category_ids( array(17) );
$set_tag = $product->set_tag_ids( [18, 19] );

Instead, it should be only:

$product->set_category_ids( array(17) );
$product->set_tag_ids( [18, 19] );

$product->save();

Then just after you will use getter methods to read the saved data and display it:

$get_cats = $product->get_category_ids();
$get_tags = $product->get_tag_ids();

var_dump($get_cats); // NOW OK
var_dump($get_tags); // NOW OK

For function.php file you should embed you code in a function like:

function my_custom_function_code(){
    // Get a new empty WC_Product instance object
    $product = new WC_Product; 

    # Setter methods (set the data)

    $product->set_name("product");
    $product->set_regular_price('150');

    $product->set_category_ids( array(17) );
    $product->set_tag_ids( [18, 19] );

    # Save the data

    $product->save(); // Always at the end to save the new data

    # Getter methods (Read the data)

    $get_cats = $product->get_category_ids();
    $get_tags = $product->get_tag_ids();

    # Display some raw data

    var_dump($get_cats); // NOW OK
    var_dump($get_tags); // NOW OK
}

Then you can use it anywhere else (like in your index.php file) simply with:

my_custom_function_code();

Upvotes: 1

Related Questions