0

For Magento 2 not logged in customer not able to access selected category any way in store Ex. url, menu, search etc , once customer logged in it will able to see category and its products.

can anyone help me how can i do this. i am new in magento 2

  • Are you using any custom theme ?? – Biren Patel Apr 17 at 6:46
  • You are using Magento commerce (EE) or open source (CE) edition of magento? – Keyur Shah Apr 17 at 7:57
  • @keyur Shah i am using magento2 (CE) – Jay Apr 17 at 8:40
  • @Biren Patel , yes – Jay Apr 17 at 8:50
  • which theme are you using? – Biren Patel Apr 17 at 9:23
3

for that you need to create the categories in configuration like in your system.xml you need to add

<field id="category" translate="label" type="multiselect"
                    sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Hide Category</label>
                    <source_model>Vender\Module\Model\Config\Source\Category</source_model>
                    <depends>
                        <field id="enabled">1</field>
                    </depends>
                </field>

now you can the Vender\Module\Model\Config\Source\Category address in this address you need to create the class to get all the categories for that you need to write

<?php
namespace Vender\Module\Model\Config\Source;

use Magento\Framework\Option\ArrayInterface;

class Category implements ArrayInterface{

    protected $_categoryFactory;
    protected $_categoryCollectionFactory;

    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory
    ) {
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_categoryFactory = $categoryFactory;
    }

    /**
    * Get category collection
    *
    * @param bool $isActive
    * @param bool|int $level
    * @param bool|string $sortBy
    * @param bool|int $pageSize
    * @return \Magento\Catalog\Model\ResourceModel\Category\Collection or array
    */


    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
    {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');

        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }

        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }

        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }

        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize);
        }

        return $collection;
    }



    public function toOptionArray(){

        $arr = $this->_toArray();
        $ret = [];
        foreach ($arr as $key => $value){
            $ret[] = [
                'value' => $key,
                'label' => $value
            ];
        }    
        return $ret;
    }




    private function _toArray(){

        $categories = $this->getCategoryCollection(true, false, false, false);
        $catagoryList = array();
        foreach ($categories as $category){
           $catagoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
        }
        return $catagoryList;
    }



    private function _getParentName($path = ''){
        $parentName = '';
        $rootCats = array(1,2);  
        $catTree = explode("/", $path);
        array_pop($catTree);     
        if($catTree && (count($catTree) > count($rootCats))){
            foreach ($catTree as $catId){
                if(!in_array($catId, $rootCats)){
                    $category = $this->_categoryFactory->create()->load($catId);
                    $categoryName = $category->getName();
                    $parentName .= $categoryName . ' -> ';
                }
            }
        }
        return $parentName;
    }
}

after that you will get all the categories like enter image description here

now after that you need to get the selected values from the categories which you selected to now showed for the customer who are not logged in for that you need to create the helper file Vender\Module\Helper\Data.php

  public function categoryData()
    {
        $getarray = $this->scopeConfig->getValue('vender_module/general/category',
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        return explode ( ',',$getarray);
    }

so after you'll get all the data of categories in the form of array now after that you need to override the home page widget and list.phtml and just give the condition

if(mycategory == 'xyz'){
//go to homepage
}
  • Thank you Brother your code working, but how can i filter categories for not logged in customer on frontend and where ? in list.phtml it give loaded category products. I need to filter categories, please help me i think am close to solution – Jay Apr 17 at 10:27
  • ok first of all if this code is working for you then please press the tick. now you want to get the specific categories??? which will be not shown for customer if not logged in? – Asad Khan Apr 17 at 10:38
  • yes i want specific category to not showing for not logged in customer – Jay Apr 17 at 10:49
  • OK now as you can see in my code helper class Data.php in this I created the function categoryData() this function will return the categories you select in the configuration... (you will select those categories which you want to hide for not logged In customer). it will return the values in the form of array e.g array[1,2..] these 1 or 2 or anything else is the category ID... – Asad Khan Apr 17 at 10:56
  • after getting these category Ids now your problem is to not allow the not Logged-In customer to go to specific Categories which you get from the function. now you'll create a one more function in the helper using Registry to get current category after that you just need to apply a simple if condition – Asad Khan Apr 17 at 11:19
0

You can create a custom module (as described below) to do this requirement.

Assume your custom module name is "Company_CategoryShowhide"

step 1) Create InstallData.php under /app/code/Company/CategoryShowhide/Setup to cutom category attribute. Attribute code is "ishide_forguest"

File: /app/code/Company/CategoryShowhide/Setup/InstallData.php

<?php

namespace Pritam\Company\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;



class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory) {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(\Magento\Catalog\Model\Category::ENTITY, 'ishide_forguest', [
            'type'     => 'int',
            'label'    => 'Hide For Guest',
            'input'    => 'boolean',
            'source'   => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
            'visible'  => true,
            'default'  => '0',
            'user_defined' => true,
            'required' => false,
            'global'   => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
            'group'    => 'Display Settings',
        ]);
    }
}

step 2) Create file category_form.xml under /app/code/Company/CategoryShowhide/view/adminhtml/ui_component to display the custom attribute in admin category add/edit form

File: /app/code/Company/CategoryShowhide/view/adminhtml/ui_component/category_form.xml

<?xml version="1.0"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="display_settings">
        <field name="ishide_forguest">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">boolean</item>
                    <item name="formElement" xsi:type="string">checkbox</item>
                    <item name="label" xsi:type="string" translate="true">Hide For Guest Customer</item>
                    <item name="prefer" xsi:type="string">toggle</item>
                    <item name="valueMap" xsi:type="array">
                        <item name="true" xsi:type="string">1</item>
                        <item name="false" xsi:type="string">0</item>
                    </item>
                    <item name="default" xsi:type="number">0</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

step 3) Create di.xml under /app/code/Company/CategoryShowhide/etc/frontend for the category plugin to override functions of Magento\Catalog\Model\Category model

File: /app/code/Company/CategoryShowhide/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">   
    <type name="Magento\Catalog\Model\Category">
        <plugin name="guest-hidecategory" type="Company\CategoryShowhide\Plugin\Category" sortOrder="1" />        
    </type>
</config> 

step 4) Create the plugin class file Category.php under /app/code/Company/CategoryShowhide/Plugin

File: /app/code/Company/CategoryShowhide/Plugin/Category.php

<?php
namespace Company\CategoryShowhide\Plugin;

use Magento\Customer\Model\Session as CustomerSession;


class Category
{               

    protected $customerSession;

    /** @var ConfigProvider */
    protected $configProvider;

    public function __construct(CustomerSession $customerSession)
    {
        $this->customerSession = $customerSession;        
    }

    public function afterGetIsActive(\Magento\Catalog\Model\Category $category)
    {       

        if (!$this->customerSession->isLoggedIn() && $category->getIshideForguest())
        {
           return false;
        }else{
            return true;
        }    

    }    

}

step 5: Run following commands from CLI

sudo php bin/magento setup:di:compile

  • Brother your code is not working for me. it appear blank page – Jay Apr 17 at 12:36
  • where did you getting a blank page? in Frontend or Backend ?. – Pritam Info 24 Apr 17 at 12:58
  • i have getting on Frontend – Jay Apr 17 at 14:03

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.