Tidjy
Tidjy

Reputation: 27

How to add a default category to a product in Prestashop programmatically?

I'm working on Prestashop 1.7 and i'm trying to create a product programmatically. Everything works like intended. I can create my product with name, price, descriptions, rules, images, etc... BUT one thing does not work: The default category. I can add categories to my product but the default is never saved.

Here my code:*

$product = new Product();
$product->name = 'Product 1';
$product->price = 100;
$product->description = 'Description 1';
$product->categories = array(1, 2, 3);
$product->default_category_id = array(4);
// ...
$product->add();

// Categories need to be added after the product creation
// Add the default category to the product
$product->updateCategories($product->default_category_id);
// Add categories to the product
$product->updateCategories($product->categories);

Categories are added to my product but not the default. So my product is created without default category. I tried with the addToCategories method too but the result is same.

I think addToCategories and updateCategories are removing previous registered categories to the product before adding the new ones.

Upvotes: 1

Views: 606

Answers (1)

joseantgv
joseantgv

Reputation: 2023

The field name is id_category_default and it expects and int:

$product = new Product();
$product->name = 'Product 1';
$product->price = 100;
$product->description = 'Description 1';
$product->categories = array(1, 2, 3);
$product->id_category_default = 4;
// ...
$product->add();

Upvotes: 1

Related Questions