Magento 2 Programatically Change Category Attribute For All Store View

In this blog post we will change value of url_key for a category in Magento 2, similar step can be followed for changing any attribute in Magento 2.

Step 1

Firstly you need to inject category model factory in your constructor.

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Catalog\Model\CategoryFactory $categoryModelFactory,
   \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->_categoryModelFactory = $categoryModelFactory;
       $this->_storeManager = $storeManager;

Step 2

Now write the below code in your function

	$this->_categoryModelFactory = $this->_categoryModelFactory->create();
        $categoryCollection = $this->_categoryModelFactory->getCollection()->addAttributeToSelect('*');
        $stores = $this->getStores();
        foreach($categoryCollection as $collection){
            if($collection->getData('url_key')) {
                if($collection->getData('entity_id') == 20) {
                    foreach($stores as $store){
                    $this->_categoryModelFactory->setData('store_id', $store);
                    $this->_categoryModelFactory->setData('url_key', 'women');

Above we have used if statement and just changed url_key for a category with entity_id as 20, you can modify according to your requirement.
Also to get store list you need to write below function:-

public function getStores($withDefault = false, $codeKey = false)
        $stores = [];
        // for 'all store view' in admin you need to seperately set id 0
        $stores[] = 0;
        foreach ($this->_storeManager->getStores() as $store) {
            $stores[] = $store->getStoreId();
        return $stores;


    • The parent_id is updating fine, you can check in catalog_category_entity but you are trying to see change in category tree I suppose for that you have to change path also for affected category and its sub-category.

  1. Hi there, I would like to subscribe for this website to obtain hottest updates, thus where can i do it please assist.


Leave a Comment.