Magento – Programmatic category update not taking effect until Save in Admin

categorymodel

I have a script that looks something like

$parent = Mage::getModel("catalog/category")->load(50);
$parent->setCustomUseParentSettings(false);
$parent->setCustomApplyToProducts(false);
$parent->setPageLayout("two_columns_left");
$parent->save();

And when I look at the category in Manage Categories of the Admin, I can see that the values updated correctly, but when I look on the frontend, I see it's still using a different layout.

All I do then is click "Save" without modifying anything, and then it renders correctly on the front page.

I've tried reindexing Category Flat tables, but this is the only way I've been able to fix this. There's ~2000 categories so saving them all isn't a solution. How can I do this programmatically? Why doesn't it work in the first place?

Best Answer

there is a trick involved as Magento only allows category save on EAV structure and it differences this (if you ask for category model) in code by checking admin store scope so you have to fake the scope to be able to save the categories if you are doing this outside of admin

$currentStore = Mage::app()->getStore()->getId();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$parent = Mage::getModel("catalog/category")->load(50);
$parent->setCustomUseParentSettings(false);
$parent->setCustomApplyToProducts(false);
$parent->setPageLayout("two_columns_left");
$parent->save();
// set the store scope back
Mage::app()->getStore()->setId($currentStore);