Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
product_with_category.php
Go to the documentation of this file.
1 <?php
17 
21 require __DIR__ . '/../../Store/_files/store.php';
22 
23 $objectManager = Bootstrap::getObjectManager();
24 
25 // reindex catalog search to create store's specific temporary tables
26 $indexerRegistry = $objectManager->create(IndexerRegistry::class);
27 $indexerRegistry->get(Fulltext::INDEXER_ID)
28  ->reindexAll();
29 
31 $category = $objectManager->create(Category::class);
32 $category->setName('category 1')
33  ->setUrlKey('cat-1')
34  ->setIsActive(true)
35  ->setStoreId(1);
36 
38 $categoryRepository = $objectManager->get(CategoryRepositoryInterface::class);
40 
42 $storeManager = $objectManager->get(StoreManagerInterface::class);
43 
44 // change default store, otherwise store won't be updated for the category
45 $storeManager->setCurrentStore($store->getId());
46 $category->setUrlKey('cat-1-2')
47  ->setUrlPath('cat-1-2')
48  ->setStoreId($store->getId());
49 
51 // back to default store
52 $storeManager->setCurrentStore(1);
53 
55 $product = $objectManager->create(Product::class);
56 $product->setStoreId(0)
57  ->setTypeId(Type::TYPE_SIMPLE)
58  ->setName('p002')
59  ->setSku('p002')
60  ->setAttributeSetId(4)
61  ->setWebsiteIds([1])
62  ->setPrice(10)
63  ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
64  ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
65  ->setStockData(
66  [
67  'use_config_manage_stock' => 1,
68  'qty' => 100,
69  'is_qty_decimal' => 0,
70  'is_in_stock' => 1,
71  ]
72  )
73  ->setQty(100)
74  ->setWeight(1);
75 
77 $productRepository = $objectManager->get(ProductRepositoryInterface::class);
79 
81 $linkManagement = $objectManager->get(CategoryLinkManagementInterface::class);
82 $linkManagement->assignProductToCategories($product->getSku(), [Category::TREE_ROOT_ID, $category->getEntityId()]);
defined('TESTS_BP')||define('TESTS_BP' __DIR__
Definition: _bootstrap.php:60