cancel
Showing results for 
Search instead for 
Did you mean: 

Can anyone tell me how to do this in mag 2?

Can anyone tell me how to do this in mag 2?

In magento 1 I was able to list all products in an external php script with the following:

 

require_once"$rootpath/app/Mage.php";
umask(0);
Mage::app('default');


$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('status', 1);
$products->addAttributeToFilter('visibility', 4);
$products->addStoreFilter($storeId);
$products->addAttributeToSelect('*');
$products->load();

 

Can anyone tell me how to do this in mag 2?

2 REPLIES 2

Re: Can anyone tell me how to do this in mag 2?

Hi @picku_peas 

 

You can try below code :

 

<?php
use Magento\Framework\App\Bootstrap;
 
/**
 * If your external file is in root folder
 */
require __DIR__ . '/app/bootstrap.php';
 
/**
 * If your external file is NOT in root folder
 * Let's suppose, your file is inside a folder named 'xyz'
 *
 * And, let's suppose, your root directory path is
 * /var/www/html/magento2
 */
// $rootDirectoryPath = '/var/www/html/magento2';
// require $rootDirectoryPath . '/app/bootstrap.php';
 
$params = $_SERVER;
 
$bootstrap = Bootstrap::create(BP, $params);
 
$obj = $bootstrap->getObjectManager();
 
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
 
$productId = 10;
$product = $obj->get('Magento\Catalog\Model\ProductRepository')
               ->getById($productId);
 
echo '<pre>';
print_r($product->getData());
echo '</pre>';
?>

you can change the filter based on your need !

 

Here is the reference link for the same - http://blog.chapagain.com.np/magento-2-run-code-in-external-file-script/

 

Hope it helps !

if issue solved,Click Kudos & Accept as Solution

Re: Can anyone tell me how to do this in mag 2?

Hi @picku_peas 

 

You can use below code for listing all products in an external php script:

 

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
 
$params = $_SERVER;
 
$bootstrap = Bootstrap::create(BP, $params);
 
$obj = $bootstrap->getObjectManager();
 
$state = $obj->get('Magento\Framework\App\State');
//you can use area as frontend too
$state->setAreaCode('adminhtml');

  try {
      $products = $obj->create('Magento\Catalog\Model\Product')
                                      ->getCollection();

      $products->addAttributeToFilter('status', 1);
      $products->addAttributeToFilter('visibility', 4);
      $products->addStoreFilter(1);
      $products->addAttributeToSelect('*');
       
       foreach($products as $product) {
          echo $product->getId() .'-'. $product->getName();
       }
  } catch (\Exception $e) {
      echo $e->getMessage();
  }

If my answer is useful, please Accept as Solution & give Kudos.