3

How we get simple product collection with visibility 4 (catalog/search) with script in Magento 2?

3
  • Do you want to do it programmatically? Jan 3, 2018 at 10:43
  • Yes I want to create programmatically.
    – meet
    Jan 3, 2018 at 10:45
  • Do you want this script to run in browser or terminal Jan 3, 2018 at 11:09

3 Answers 3

2

Try following code:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

use Magento\Framework\App\Bootstrap;

try{

    require __DIR__ . '/app/bootstrap.php';

    $params = $_SERVER;
    $bootstrap = Bootstrap::create(BP, $params);
    $obj = $bootstrap->getObjectManager();
    $obj->get('Magento\Framework\Registry')->register('isSecureArea', true);
    $appState = $obj->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');

    $products = $obj->create('\Magento\Catalog\Model\Product')->getCollection();
    $products->addAttributeToSelect(array('name'))
        ->addFieldTofilter('type_id','simple')
        ->addFieldToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
        ->addFieldToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
        ->load();

    echo "Total products count: " . $products->count() . "<hr>";
    echo "<pre>";
    if ($products->getSize() > 0) {
        foreach ($products as $product) {
            print_r($product->getData());
        }
    }

} catch (Exception $e) {
    echo $e->getMessage();
}
1
  • @meet - Happy to help. Keep helping :)
    – Pratik Oza
    Jan 3, 2018 at 11:24
0
$om = \Magento\Framework\App\ObjectManager::getInstance();

/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $om->get(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);
$collection->addFieldToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);

foreach ($collection->getItems() as $product) {
    var_dump($product);
}
0

Following is a controller for getting collection of all simple products whose visibility is set to catalog,search

<?php
namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Context;

class GetProducts extends \Magento\Framework\App\Action\Action
{
    private $productModel;

    public function __construct(
        Context $context,
        \Magento\Catalog\Model\ProductFactory $productModel
     ) {
         $this->productModel = $productModel;
         parent::__construct($context);
        }

    public function execute()
    {
            $collection = $this->productModel->create()->getCollection()->addAttributeToFilter('visibility','4')->addAttributeToFilter('type_id', \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);

    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.