Question

I want to check whether my current category in Anchored in Magneto 2

Was it helpful?

Solution

According to the comments and requriement mentioned you can try the below logic: Through Objectmanager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$xmlLayout = $objectManager->get(\Magento\Framework\App\View::class);
$loadedHandles = $xmlLayout->getLayout()->getUpdate()->getHandles();

Through class injection:

public function __construct(
    \Magento\Framework\App\ViewInterface $view
){
    $this->view = $view;
}

Use the below code to get loaded handles:

$loadedHandles = $this->view->getLayout()->getUpdate()->getHandles();

For isAnchored you will get below:

Array
(
    [0] => default
    [1] => catalog_category_view
    [2] => catalog_category_view_type_layered
    [3] => catalog_category_view_type_layered_without_children
    [4] => catalog_category_view_id_4
)

And for Non-Anchored you will get below:

Array
(
    [0] => default
    [1] => catalog_category_view
    [2] => catalog_category_view_type_default
    [3] => catalog_category_view_id_20
    [4] => catalog_category_view_layout_update_680a89c63ad8009fef6e1a9900eab84e
)

You can now use php in_array function to check your logic.

OTHER TIPS

Pass category ID as per your requirement :

$categoryId = 17;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$object_manager = $_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);

echo "<pre>";
print_r($object_manager->getData());

Note : Use of objectManager is not good idea. Instead of this you can use DI.

Check here

1 = Is Anchor 0 = Not Anchor

private $categoryRepository;

public function __construct(
    \Magento\Catalog\Model\CategoryRepository $categoryRepository
) {
    $this->categoryRepository = $categoryRepository;
}

public function getCategoryAnchor() {
    $categoryId = '15'; // your category id
    $category = $this->categoryRepository->get($categoryId);

    if ($category->getIsAnchor()) {
        // your custom code
    }
}

EDIT As per your requirements, i think you need to find out the current layout used for current category, so try the below code :

If you are using .phtml file

then use

$block->getLayout()->getUpdate()->getPageLayout()

If you are using block class

$this->getLayout()->getUpdate()->getPageLayout()

You can check using Magento\Catalog\Model\CategoryFactory as follows:

protected $_category;

public function __construct(
    \Magento\Catalog\Model\CategoryFactory $category
) {
    $this->_category = $category;
}

public function execute() {
    $category = $this->_category->create()->load($id);
    var_dump($category->getIsAnchor()); // string "0" or "1"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top