How can I programatically change url-key for a category for all store views?
1 Answer
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->load($collection->getData('entity_id'));
$this->_categoryModelFactory->setData('store_id', $store);
$this->_categoryModelFactory->setData('url_key', 'women');
$this->_categoryModelFactory->save();
}
}
}
}
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.
-
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. Commented Apr 21, 2017 at 9:07
-
How many stores do you have, I am getting store array correctly.– arushiCommented Apr 21, 2017 at 11:26
-
I have one. I resolved the problem by setting the $c->setStoreId(0); $c->save(); and $c->setStoreId(1); $c->save(); Commented Apr 21, 2017 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– arushiCommented Apr 21, 2017 at 12:17
-
1Please 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. Commented Sep 18, 2017 at 15:09