Thứ Ba, 30 tháng 5, 2017

How to get product is filter to url category


You can get all product of  category you want.

p/s: 
->addAttributeToFilter('url_key','xxx')  | xxx: is url category.
->addFieldToFilter("type_id", array('neq' => 'configurable'))  | You not get all product include configurable.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $categoryFactory = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
    $topCategory = $categoryFactory->create()
    ->addAttributeToFilter('url_key','top-products')
    ->addAttributeToSelect('*')
    ->getFirstItem();
    $topCollection = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
    $topCate = $topCollection->create()
    ->addAttributeToSelect('*')
    ->addCategoryFilter($topCategory)
    ->addFieldToFilter("type_id", array('neq' => 'configurable'))
    ->addAttributeToFilter('status', '1')
    ->setPageSize(4)
    ->setOrder('created_at', 'DESC')->load();
?>

And then you can use foreach for do loop product.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<div class="row section-top open">
    <?php  foreach ($topCate as $product){ ?>
    <div class="col-md-3 custom-resize">
        <div class="box-img">
            <a href="<?= $product->getProductUrl()?>">
                <img src="<?= $mediaUrl ."catalog/product". $product['image'] ?>" alt="<?= $product->getName()?>">
            </a>
        </div>
        <h4><a href="<?= $product->getProductUrl()?>"><?= $product->getName()?></a></h4>
        <?php $specialPrice = $product->getSpecialPrice(); 
        if(!is_null($specialPrice)){?>
        <span class="price-single"><a href="<?= $product->getProductUrl()?>"><?=  "$".number_format($product->getPrice(), 2); ?></a></span>
        <span class="special_price"><a href="<?= $product->getProductUrl()?>"><?= "$".number_format($product->getSpecialPrice(), 2);?></a></span>
        <?php }
        else{ ?>
        <span class="single-price"><a href="<?= $product->getProductUrl()?>"><?=  "$".number_format($product->getPrice(), 2); ?></a></span>
        <?php } ?>
    </div>
    <?php } ?>
</div>

Không có nhận xét nào:

Đăng nhận xét

About me

Recent

recentposts

Random

randomposts