How can I set zero price for simple product programmatically?
If I set:
$product->setPrice(0);
In admin panel price field is empty. If I save this product - system return error - price field is empty.
Try to load product by SKU & Factory class:
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$productFactory = $objectManager->create(\Magento\Catalog\Model\ProductFactory::class);
// Load the product by SKU or any other identifier
$sku = 'your_product_sku_here';
$product = $productFactory->create()->loadByAttribute('sku', $sku);
if ($product) {
// Set the price to zero
$product->setPrice(0);
// Save the product
$product->save();
echo "Zero price set for product with SKU: $sku";
} else {
echo "Product with SKU $sku not found";
}
I tried above code & it's working fine.
Create a PHP script in the root directory of your Magento installation (e.g., set_zero_price.php
).
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '../../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
// Load product by SKU
$productSku = 'YOUR_PRODUCT_SKU_HERE';
$product = $objectManager->create('\Magento\Catalog\Model\Product')->loadByAttribute('sku', $productSku);
if ($product) {
// Set price to zero
$product->setPrice(0);
$product->save();
echo "Price for product with SKU $productSku set to zero.";
} else {
echo "Product with SKU $productSku not found.";
}
Run the script in the command line or through a browser to execute it:
php set_zero_price.php
Let me know If any quries.
Thanks.