Tuesday, September 6

How to get current currency and currency symbol in Magento

here is the script to get current currency & Currency symbol in Magento

for current currency
$currency_code = Mage::app()->getStore()->getCurrentCurrencyCode(); 

for currency symbol
Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();

Hope it helps... Thanks....

How to get Order Increment ID in Magento

Here is the script to increment the order id in magento

$order = Mage::getModel('sales/order');
$order->load(Mage::getSingleton('sales/order')->getLastOrderId());
$lastOrderId = $order->getIncrementId();

Last real order id

Mage::getSingleton('checkout/session')->getLastRealOrderId();

Hope it helps.. Thanks...

How to Re-Index manually using SQL query in Magento

Here is the script to reindex the data in magento

getConnection('core_write');
    $mysqli->query($sql);
    /*
    Process_id     Indexer_code
        1     catalog_product_attribute
        2     catalog_product_price
        3     catalog_url
        4     catalog_product_flat
        5     catalog_category_flat
        6     catalog_category_product
        7     catalogsearch_fulltext
        8     cataloginventory_stock
        9     tag_summary
    */
    $process = Mage::getModel('index/process')->load(7);
    $process->reindexAll();
    echo "Finished Rebuilding Search Index At: " . date("d/m/y h:i:s");
?>

Hope it helps... Thanks...

How to get Product Image path in Magento

Here is the script to get product image path in magento

$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::helper('catalog/image')->init($product, 'image')->resize(75, 75);


Hope it Helps... Thanks

Monday, September 5

How to change Admin URL Path in Magento

Here is a quick guide on how to change admin url path in Magento. This need to be done for security reason to be safe from hacking/cracking issue. Basically, this is done not to let any general user to access the admin page.

Generally, we do have ‘admin‘ as the administrator path for Magento. So, the admin URL will be http://www.example.com/admin/

This article will show you, how you can change the admin url. Let’s say from ‘admin‘ to ‘backend‘. So, the new admin URL will be http://www.example.com/backend/

Here is how we do it:-

- Open app/etc/local.xml
- Find the following:-

<admin>
    <routers>
            <adminhtml>
                <args>
                    <frontName><![CDATA[admin]]></frontName>
                </args>
            </adminhtml>
        </routers>
</admin>

- Change

<frontName><![CDATA[admin]]></frontName>

to your desired name. Like below:-

<frontName><![CDATA[backend]]></frontName>

- Save the file
- Refresh the Cache from Magento Admin (System -> Cache Management)

Now, you should be able to access admin panel from http://www.example.com/backend/ instead of http://www.example.com/admin/
Important Note

If you just need to change the admin base URL then the proper way I find is by doing the change in local.xml like explained above, instead of editing configuration setting from admin like said below.

I tried to change the Admin Base URL from Magento admin panel. But, I ran into problem and could not access the admin after that. Here is what I did:-

- System -> Configuration -> ADVANCED -> Admin -> Admin Base URL
- Changed Use Custom Admin URL = Yes
- Changed Custom Admin URL (Once I tried with ‘backend/’ and then with ‘http://www.example.com/backend/’)

To solve the problem, I had to make some change in database. If you had similar problem then here is a workaround:-

- Open your database
- Browse table ‘core_config_data‘
- Search in path field for ‘admin/url/use_custom‘ and set its value to ’0′
- Search in path field for ‘admin/url/custom‘ and set its value to empty

- Search in path field for ‘web/secure/base_url‘
- You will find two row result. One with scope = default and another with scope = stores.
- Edit the value of row with scope = stores with the value of the row with scope = default

- Similarly, repeating the process for ‘web/unsecure/base_url‘:-

- Search in path field for ‘web/unsecure/base_url‘
- You will find two row result. One with scope = default and another with scope = stores.
- Edit the value of row with scope = stores with the value of the row with scope = default

- Now, you will be able to login to Magento admin with your old admin base URL.

Ref : http://blog.chapagain.com.np/magento-how-to-change-admin-url-path/

How to Sort latest product by ‘created date’ and ‘new from date’ in Magento

Here is a quick tip to sort/order latest product by both created date and new from date.

Created At date is automatically added when you add a new product. However, you have to set New from Date manually while adding or editing product.

You may have product with same new from date. And, then you need created at date to sort the latest product.

Here is the code to sort/order product by both created date and new from date:-

$todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
 
$collection = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter('news_from_date', array('date' => true, 'to' => $todayDate))
                    ->addAttributeToFilter('news_to_date', array('or'=> array(
                        0 => array('date' => true, 'from' => $todayDate),
                        1 => array('is' => new Zend_Db_Expr('null')))
                    ), 'left')
                    ->addAttributeToSort('news_from_date', 'desc')
                    ->addAttributeToSort('created_at', 'desc');

Thanks to Mukesh Chapagain's Blog
Reference : http://blog.chapagain.com.np/magento-sort-latest-product-by-created-date-and-new-from-date

How to disable / remove Secret Key from Admin URL in Magento

A new secret key is created every time you login to Magento Admin. So, there will be a unique key (32 chars long) for each session of your Magento admin login. This key is appended to the admin URL as http://your-admin-url/key/743c37b1…adf6588/

This is basically added for security reason. In their release note, Magento say that they added secret key to URL for CSRF (Cross-site request forgery) Attack Prevention.

Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user’s browser.

You can learn more about CSRF here:- http://en.wikipedia.org/wiki/Cross-site_request_forgery

Sometime you may want to access admin URL without the secret key. For this, you can disable the secret key from admin URL.

Here is how you do it:-

- Login to admin
- Go to System -> Configuration -> ADVANCED -> Admin -> Security -> Add Secret Key to URLs
- Select No
- Save Config

You are done. You will not see the secret key in admin URL nowonwards.

Thanks to Mukesh Chapagain's Blog
Reference : http://blog.chapagain.com.np/magento-how-to-disable-remove-secret-key-from-admin-url

Can’t send header. Header is already sent” in Magento - Tips to solve the problem

In this article I will show you quick tip that will help you solve common problems in Magento: “Can’t send header. Header already sent” in Magento.

I got this error when I have managed to bring back the client store. Basically, this error happens when there is an extra space or character outside the the php tag . Thanks to the help of excellent Magento users, I have been able to solve it. I think it will be useful if I explained steps by steps what I personally have done so that you can reference it later. When this error happens, you should try the following things.

Open the file that has the problem. In my case, this file is index.php in the site root of Magento.

Open the file with some text editors that supports the encoding. I prefer Notepad++ because its great support in multi languages as well as encoding.

If you open it by Notepad++, click on the menu Encoding, click on UTF-8 without BOM. Save it and then re-upload it to the server.

We just save the error file in the UTF-8 encoding to make sure that everything extra space, line is wiped out. Encoding without BOM ensures you will not have any extra, unwanted characters in the file that prevent it from being executed properly.

Hope it Helps... Thanks..

Friday, August 19

How to get all store details in Magento

Here is the script to get all store details in Magento

<?php
$allStores = Mage::app()->getStores();
foreach ($allStores as $_eachStoreId => $val)
{
$_storeCode = Mage::app()->getStore($_eachStoreId)->getCode();
$_storeName = Mage::app()->getStore($_eachStoreId)->getName();
$_storeId = Mage::app()->getStore($_eachStoreId)->getId();
echo $_storeId;
echo $_storeCode;
echo $_storeName;
}
?> 

Hope it helps... Thanks....

Wednesday, August 10

Frequently Used Methods in Magento

1. Check if customer is logged in:
if(!Mage::getSingleton('customer/session')->isLoggedIn())
{
 $this->_redirect('customer/account/login/');
}

2. Get current site url:
<?php Mage::getUrl(); ?>

3. Get Category URL:
$categoryUrl = Mage::getModel('catalog/category')->load($categoryId)->getUrl(); 

4. Get product URL:
$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::getUrl().$product->getUrlPath();

5. Get Product image path:
$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::helper('catalog/image')->init($product, 'image')->resize(75, 75);

6. Format a number as price:
<?php $this->formatPrice(10);?>

7. Call a .phtml explicitly:
echo $this->getLayout()->createBlock('sales/order_recent')->setTemplate('sales/order/recent.phtml')->toHtml();


8. Get Currency Code:
Mage::app()->getStore()->getCurrentCurrencyCode();

9. Get Currency Symbol:
Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();

10. Get Customer Shipping/Billing Address:
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping();
if ($customerAddressId){
       $address = Mage::getModel('customer/address')->load($customerAddressId);
}

11. Get products details in the cart:
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
 
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
 
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item) 
{
 $productid      = $item->getProductId();
 $name       = $item->getName();
 $qty       = $item->getQty();
  
 echo "Product Id-".$productid.', Name-'.$name. ', Quantity-'.$qty;
}

12. Find which class is loaded in current template:
<?php
    print_r(get_class_methods(get_class($this)));
?>
or
<?php
    print_r($this->debug());
?>
or
<?php
    echo Zend_Debug::dump($this);
?>

13. Get Current theme folder:
<?php echo $this->getSkinUrl('') ?>

14. Get total price of items in the cart:
<?php echo $this->helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal()); ?>

15. Get the current category:
<?php
    $currentCategory = Mage::registry('current_category');
?>
16. Add product to cart through querystring:
http://www.mydomain.com/checkout/cart/add?product=[id]&qty=[qty]
 
http://www.mydomain.com/checkout/cart/add?product=[id]&qty=[qty]&options[id]=[value]

These are the some of the frequently used functions in Magento

Hope it Helps... Thanks..