1

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

  • may i know whether you are looking for the the code to implement the api ? – Nagaraju K Aug 7 '17 at 6:19
2

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.

  • No issues, the code is working fine....thank you.. – srg Aug 7 '17 at 6:31
  • @glad to hear that – Rajkumar .E Aug 7 '17 at 6:34
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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