I have one question about showing products. I dont want to show products for guest user. Even when they search for those products they will not get that. Only logged in user will get those.
Can anyone give me some tips how we can implement this?
I have one question about showing products. I dont want to show products for guest user. Even when they search for those products they will not get that. Only logged in user will get those.
Can anyone give me some tips how we can implement this?
You may use a plugin after Magento\Catalog\Model\Product::getVisibility()
and set the return value to Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE
if you have a guest user (i.e. the customer is not logged in) and your product attribute is set.
Your custom attribute needs to be available in product lists otherwise loading a specific product collection could miss it.
If customer is not logged-in you can restrict customer from category and product page.
Check the following module
vendor/magento/module-website-restriction/Observer/RestrictWebsite.php
You can add custom controller path in "webrestrictions.xml" if you override this file in your module
vendor/magento/module-website-restriction/etc/webrestrictions.xml
Alternate solution you can use before Plugin for below class for execute method
vendor/magento/module-catalog/Controller/Product/View.php
vendor/magento/module-catalog/Controller/Category/View.php
You can use events in this approach
event name = catalog_block_product_list_collection
in the execute function you can remove all products like this
add events.xml to your module
etc/frontend/events.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_block_product_list_collection">
<observer instance="{vendor}\{module}\Observer\Frontend\Catalog\BlockProductListCollection" name="{vendor}_{module}_observer_frontend_catalog_blockproductlistcollection_catalog_block_product_list_collection"/>
</event>
</config>
and this code to your observer file
/app/code/{Vendor}/{Module}/Observer/Catalog/BlockProductListCollection.php
<?php
namespace {Vendor}\{Module}\Observer\Catalog;
class BlockProductListCollection implements \Magento\Framework\Event\ObserverInterface
{
public function execute(
\Magento\Framework\Event\Observer $observer
) {
// if(customer is not loggedin)
$collection = $observer->getEvent()->getCollection();
foreach ($collection as $k => $product){
$collection->removeItemByKey($k);
}
}
}