Magento ver. 2.4.2-p1
I have a Magento install with 3 unique websites. I need to export products for only 1 website at a time.
There does not appear to be an option for this in:
- System - Export - Entity type = Products
How to best do this?
Run below script :
protected $storeManager;
protected $productCollectionFactory;
protected $csvProcessor;
public function __construct(
StoreManagerInterface $storeManager,
CollectionFactory $productCollectionFactory,
Csv $csvProcessor
) {
$this->storeManager = $storeManager;
$this->productCollectionFactory = $productCollectionFactory;
$this->csvProcessor = $csvProcessor;
}
public function execute()
{
$websiteId = 1; // Change this to the ID of the target website
$productCollection = $this->productCollectionFactory->create();
$productCollection->addWebsiteFilter($websiteId);
$exportData = [];
$exportData[] = ['sku', 'name', 'price']; // Add more fields as needed
foreach ($productCollection as $product) {
$exportData[] = [$product->getSku(), $product->getName(), $product->getPrice()]; // Add more fields as needed
}
// Generate and save the CSV file
$exportPath = $this->getExportPath(); // Define a method to get the export file path
$this->csvProcessor->saveData($exportPath, $exportData);
}
private function getExportPath()
{
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$exportPath = 'export/products_for_website.csv';
return $mediaDirectory->getAbsolutePath($exportPath);
}