Mini Tutorial: Updating Products in Magento Within Website Scope

November 5, 2012 by Corey

Sometimes in Magento you need to write some code to update products programmatically. This may go hand in hand with wanting to batch update products within a certain store or website scope. Recently we needed to be able to specify which websites should be updated with the ‘price’ attribute. A couple issues stood in our way.

The first being that the scope of all price attributes (price, special price, special from date, special to date, etc.) were not managed in the ‘Manage Attributes’ section in the Magento backend as one would assume. Instead, they can be found in System > Configuration > Catalog > Catalog > Price > Price Scope. You can either choose ‘Global’ (meaning across all websites) or ‘Website’ (for website specific pricing, as we are wanting.) We cannot choose ‘Store’ scope.

We can now use the following code in a function to adjust the price programatically for specific website codes. You’ll also notice below that we set the store to the admin store, something I struggled with. We must set the admin store first, and then set the scope of the specific product later ($product->setStoreId($store->getStoreId());) You may also notice lines like this: $product->setSpecialToDateIsFormated(true);. We need these to pass in a date as a string and tell Magento that it is indeed a date and should be stored that way.

public function updateSpecialPriceByWebsite($price, $specialFromDate, $specialToDate, $sku, $website)
    {
        try {
            $specialFromDate = date('Y-m-d', strtotime($specialFromDate));
            $specialToDate = date('Y-m-d', strtotime($specialToDate));
            $website = Mage::app()->getWebsite($website);
            Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
            $store = $website->getDefaultStore();
            $product = Mage::getModel('catalog/product');
            $productId = $product->getIdBySku($sku);
            $product->load($productId);
            if ($product && $product->getId()) {
                $product->setStoreId($store->getStoreId());
                $product->setSpecialFromDate($specialFromDate);
                $product->setSpecialFromDateIsFormated(true);
                $product->setSpecialToDate($specialToDate);
                $product->setSpecialToDateIsFormated(true);
                $product->setSpecialPrice(strval($price));
                $product->save();
                return true;
            }
        } catch (Exception $e) {
            Mage::logException($e);
            return false;
        }

        return true;
    }

Hope this helps someone!

About Corey

Certified Magento Developer

Read more posts by Corey