How can I programatically change url-key for a category for all store views?

| improve this question | | | | |
  • you can change it from category > search engine optimization > url key – arushi Apr 20 '17 at 14:36
  • I need a programmatic solution, not manual. I need to change by using the code. – Vladimir Despotovic Apr 20 '17 at 14:41

You can use below code to change url_key for category for all store. we do not have direct function to change for all store so looping is added according to stores.

$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');

To get the store list add below code:-

// for 'all store view in admin'
    $stores[] = 0;
    foreach ($this->_storeManager->getStores() as $store) {

        echo $store->getStoreId();
        $stores[] = $store->getStoreId();

Hope this will help you out, let me know if you found any issue.. You can use this link for more details.

| improve this answer | | | | |
  • When I run your loop for stores, I only get one store, with id=1. However, I also have the "All Store Views" on my admin page, and on this page, the categories look different than on the storeId=1. – Vladimir Despotovic Apr 21 '17 at 9:07
  • How many stores do you have, I am getting store array correctly. – arushi Apr 21 '17 at 11:26
  • I have one. I resolved the problem by setting the $c->setStoreId(0); $c->save(); and $c->setStoreId(1); $c->save(); – Vladimir Despotovic Apr 21 '17 at 12:15
  • I am updating the answer, default(i.e, with id 0) is never listed in store list. But in future if you have more store than above code will work fine(it will give you all list. Hope this will help – arushi Apr 21 '17 at 12:17
  • 1
    Please use fitting variable names. The ones used are misleading. categoryModelFactory for example is not a factory, but a model. $collection is not a collection, but a data object. – Patrick van Bergen Sep 18 '17 at 15:09

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.