Question

programatically search products in magento 2. Please help me to get products using search criteria.

Was it helpful?

Solution

If you want to search Product programatically, try below code.

I used SKU to get Products.

Call this in your template file.

    #File: app/code/Pulsestorm/RepositoryTutorial/Command/Examples.php    

    //create our filter
    $filter_1 = $this->objectManager
    ->create('Magento\Framework\Api\FilterBuilder')
    ->setField('sku')
    ->setConditionType('like')
    ->setValue('WSH')    
    ->create();

    //add our filter(s) to a group
    $filter_group = $this->objectManager
    ->create('Magento\Framework\Api\Search\FilterGroupBuilder')
    ->addFilter($filter_1)
    ->create();

    // $filter_group->setData('filters', [$filter]);

    //add the group(s) to the search criteria object
    $search_criteria = $this->objectManager
    ->create('Magento\Framework\Api\SearchCriteriaBuilder')
    ->setFilterGroups([$filter_group])
    ->create();

    $productdata  = $this->objectManager->create('\Magento\Catalog\Model\ProductRepository')->getList($search_criteria)->getItems();  

        foreach ($productdata as $product) {
            echo  $product->getSKU();
        }

Reference: enter link description here

Let me know If you have issue.

OTHER TIPS

Please use the below code, might be useful for you. here i am giving u test script just copy and past in the test script and run the code as shown in the screenshots

EX: http://testsite.com/filename.php?q={yoursearchterm}

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$appState = $objectManager->get(\Magento\Framework\App\State::class);
$layerResolver = $objectManager->get(\Magento\Catalog\Model\Layer\Resolver::class);
$appState->setAreaCode('frontend');
$layerResolvers = $layerResolver->create('search');
$layerResolvers1 = $layerResolver->get();
$productCollection = $layerResolvers1->getProductCollection();

echo "Search layered navigation :<br>";
echo "products count == ".count($productCollection)."<br>";
foreach ($productCollection as $product) {
    echo "Name : ".$product->getName()." Price : ".$product->getPrice()."<br>";

}
?>

Screenshots: :

http://prntscr.com/g5a203

http://prntscr.com/g5a238

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top