如何在 Magento 2 中以编程方式创建可配置产品
在 Magento 2 中以编程方式创建可配置产品的步骤:
第一步:首先在Magento根目录下创建一个configurable_product.php文件,添加如下代码
<?php use Magento\Framework\AppInterface; try { require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try { $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('Magento\Framework\App\State'); $appState->setAreaCode('frontend'); $configurableproduct = $objectManager->create('Magento\Catalog\Model\Product'); $configurableproduct->setSku("configurable_sku"); // set Your SKU $configurableproduct->setName("Configurable Name"); // set Your Configurable Name $configurableproduct->setAttributeSetId(4); // set attribute id $configurableproduct->setStatus(1); // status enabled/disabled 1/0 $configurableproduct->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable) $configurableproduct->setVisibility(4); // visibility of product (Not Visible Individually (1) / Catalog (2)/ Search (3)/ Catalog, Search(4)) $configurableproduct->setPrice(0); $configurableproduct->setTaxClassId(0); // Tax class ID $configurableproduct->setWebsiteIds(array(1)); // set website Id $category_id = array(2, 3); $configurableproduct->setCategoryIds($category_id); $configurableproduct->setStockData(array( 'use_config_manage_stock' => 0, 'manage_stock' => 1, 'is_in_stock' => 1, ) ); $configurableattributesdata = $configurableproduct->getTypeInstance()->getConfigurableAttributesAsArray($configurableproduct); $configurableproduct->setCanSaveConfigurableAttributes(true); $configurableproduct->setConfigurableAttributesData($configurableattributesdata); $configurableproductsdata = array(); $configurableproduct->setConfigurableProductsData($configurableproductsdata); try { $configurableproduct->save(); } catch (Exception $ex) { echo '
'; print_r($ex->getMessage()); exit(1); } $product_id = $configurableproduct->getId(); $associatedproductids = array(1,9); try { $configurableproduct_load = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id); $configurableproduct_load->setAssociatedProductIds($associatedproductids); $configurableproduct_load->setCanSaveConfigurableAttributes(true); $configurableproduct_load->save(); echo "configurable product save successfully"; } catch (Exception $e) { echo "
"; print_r($e->getMessage()); exit(1); } }catch (Exception $e) { echo "
"; print_r($e->getMessage()); exit(1); }
第 2 步:完成上述步骤后,您需要运行下面给出的 URL 来创建可配置的产品。
https://yourdomain.com/configurable_product.php
版权声明:本站内容源自互联网,如有内容侵犯了你的权益,请联系删除相关内容。