June 26, 2015 10:56 pm
image_round

Magento Customer redirection

Magento Customer redirection

Magento Customer redirection we can redirect customer to previous page after login instead of my account dashboard

we just have to follow below steps and code

Admin – >System -> Configuration -> CUSTOMERS -> Customer Configuration -> Login Options -> Redirect Customers to Account Dashboard after Loggin in = No

setup login required to view page

add below code on page start and user will be restricted with login

<?php 
if(!Mage::helper('customer')->isLoggedIn()) {
  Mage::getSingleton('customer/session')
            ->setBeforeAuthUrl(Mage::helper('core/url')->getCurrentUrl()); 
  $this->_redirect('customer/account/login');
}
?>

redirect customer to its previous page after adding item to cart

Admin – >System -> Configuration -> Sales -> Checkout -> After Adding a Product Redirect to Shopping Cart = No

Magento Customer redirection

Magento Customer redirection

Magento Customer redirection we can redirect customer to previous page after login instead of my account dashboard

we just have to follow below steps and code

Admin – >System -> Configuration -> CUSTOMERS -> Customer Configuration -> Login Options -> Redirect Customers to Account Dashboard after Loggin in = No

setup login required to view page

add below code on page start and user will be restricted with login

<?php 
if(!Mage::helper('customer')->isLoggedIn()) {
  Mage::getSingleton('customer/session')
            ->setBeforeAuthUrl(Mage::helper('core/url')->getCurrentUrl()); 
  $this->_redirect('customer/account/login');
}
?>

redirect customer to its previous page after adding item to cart

Admin – >System -> Configuration -> Sales -> Checkout -> After Adding a Product Redirect to Shopping Cart = No

June 26, 2015 10:49 pm
image_round

Magento check module status progarmatically

Magento check module status progarmatically

Magento check module status progarmatically: Magento has function to check if module is enabled or not

The functions isModuleEnabled and another is to check it node status

<?php

$moduleName = 'Mage_Core';
if (Mage::helper('core')->isModuleEnabled($moduleName)) {
  echo "Module is enabled.";
} else {
  echo "Module is disabled.";
}

?>
<?php 

$moduleName = 'Mage_Core'; 
$isActive = Mage::getConfig()->getNode('modules/' . $moduleName . '/active');
if ($isActive && in_array((string)$isActive, array('true', '1'))) {
  echo "Module is enabled.";
} else {
  echo "Module is disabled.";
}
?>

Magento check module status progarmatically

Magento check module status progarmatically

Magento check module status progarmatically: Magento has function to check if module is enabled or not

The functions isModuleEnabled and another is to check it node status

<?php

$moduleName = 'Mage_Core';
if (Mage::helper('core')->isModuleEnabled($moduleName)) {
  echo "Module is enabled.";
} else {
  echo "Module is disabled.";
}

?>
<?php 

$moduleName = 'Mage_Core'; 
$isActive = Mage::getConfig()->getNode('modules/' . $moduleName . '/active');
if ($isActive && in_array((string)$isActive, array('true', '1'))) {
  echo "Module is enabled.";
} else {
  echo "Module is disabled.";
}
?>
June 26, 2015 10:42 pm
image_round

Magento get bestseller from category

Magento get bestseller from category

Magento get bestseller from category

Magento already uses bestseller products aggregation that can be checked under Admin > Reports > Products > Bestsellers. Thanks to this aggregated data we no longer need to determine the total of all the orders to see which products are sold the most. By the variety of aggregation data we’re able to get the most popular products not only from the beginning, but for each specific day, month or year

<?php 

$productCount = 10;  //insert how much prodect
    $storeId    = Mage::app()->getStore()->getId();      
    $collection = Mage::getResourceModel('reports/product_collection')
                  	  ->addAttributeToSelect('*')
                 	  ->addOrderedQty()
                 	  ->setStoreId($storeId)
                  	  ->addStoreFilter($storeId)
                 	  ->addCategoryFilter(Mage::registry('current_category'))
               	  ->setOrder('ordered_qty', 'desc')
              	  ->setPageSize($productCount);                  
 
                Mage::getSingleton('catalog/product_status')
                         ->addVisibleFilterToCollection($collection);
                Mage::getSingleton('catalog/product_visibility')
                         ->addVisibleInCatalogFilterToCollection($collection);    
            
?>

Magento get bestseller from category

Magento get bestseller from category

Magento get bestseller from category

Magento already uses bestseller products aggregation that can be checked under Admin > Reports > Products > Bestsellers. Thanks to this aggregated data we no longer need to determine the total of all the orders to see which products are sold the most. By the variety of aggregation data we’re able to get the most popular products not only from the beginning, but for each specific day, month or year

<?php 

$productCount = 10;  //insert how much prodect
    $storeId    = Mage::app()->getStore()->getId();      
    $collection = Mage::getResourceModel('reports/product_collection')
                  	  ->addAttributeToSelect('*')
                 	  ->addOrderedQty()
                 	  ->setStoreId($storeId)
                  	  ->addStoreFilter($storeId)
                 	  ->addCategoryFilter(Mage::registry('current_category'))
               	  ->setOrder('ordered_qty', 'desc')
              	  ->setPageSize($productCount);                  
 
                Mage::getSingleton('catalog/product_status')
                         ->addVisibleFilterToCollection($collection);
                Mage::getSingleton('catalog/product_visibility')
                         ->addVisibleInCatalogFilterToCollection($collection);    
            
?>
June 26, 2015 10:39 pm
image_round

Magento SEO friendly url

Magento SEO friendly url

Magento SEO friendly url with below 2 steps

#1 Go to Magento Admin

Go to  System > Configuration > Web > Search Engine Optimization

Use Web Server Rewrites: YES

Then Go to Cache Management page and Refresh your cache and refresh to  Check  the site.

#2 open .htaccess file from root directory and edit it

on htaccess file you will find #RewriteBase /magento/ on line 123

remove comment ‘#’ and set relative magento directory path

Magento SEO friendly url

Magento SEO friendly url

Magento SEO friendly url with below 2 steps

#1 Go to Magento Admin

Go to  System > Configuration > Web > Search Engine Optimization

Use Web Server Rewrites: YES

Then Go to Cache Management page and Refresh your cache and refresh to  Check  the site.

#2 open .htaccess file from root directory and edit it

on htaccess file you will find #RewriteBase /magento/ on line 123

remove comment ‘#’ and set relative magento directory path

June 26, 2015 10:34 pm
image_round

Magento add Multiple images to products

Magento add Multiple images to products

Magento add Multiple images to products programmatically

First Go to appcodecoreMageCatalogModelConvertAdapterProduct.php

Open Product.php file and find this Code

<?php 
   $addedFilesCorrespondence = $mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes(
         $product,$arrayToMassAdd, Mage::getBaseDir('media') . DS . 'import',false,false);
 
?>

After this put this code in File

<?php

if (isset($importData['media_gallery']) && !empty($importData['media_gallery'])) {
    $x = explode(';', $importData['media_gallery']);
    foreach ($x as $file) {
       $imagesToAdd[] = array('file' =>; trim($file));
    }
 
$mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes(
     $product,$imagesToAdd, Mage::getBaseDir('media') . DS . 'import',false,false);
}

Now open your Product’s csv file and add column named “media_gallery”

and then add images comma (‘,’) seprated like below

e.g : /s/e/second_image.png, /t/h/third_image.png,/f/o/fourth_image.png

Magento add Multiple images to products

Magento add Multiple images to products

Magento add Multiple images to products programmatically

First Go to appcodecoreMageCatalogModelConvertAdapterProduct.php

Open Product.php file and find this Code

<?php 
   $addedFilesCorrespondence = $mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes(
         $product,$arrayToMassAdd, Mage::getBaseDir('media') . DS . 'import',false,false);
 
?>

After this put this code in File

<?php

if (isset($importData['media_gallery']) && !empty($importData['media_gallery'])) {
    $x = explode(';', $importData['media_gallery']);
    foreach ($x as $file) {
       $imagesToAdd[] = array('file' =>; trim($file));
    }
 
$mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes(
     $product,$imagesToAdd, Mage::getBaseDir('media') . DS . 'import',false,false);
}

Now open your Product’s csv file and add column named “media_gallery”

and then add images comma (‘,’) seprated like below

e.g : /s/e/second_image.png, /t/h/third_image.png,/f/o/fourth_image.png

June 26, 2015 10:28 pm
image_round

Magento create frontend editor

Magento create frontend editor

Magento create frontend editor like backend with just few below code

add below code to layout.xml file of module

<default>
<reference name="head">
<action method="setCanLoadExtJs"><flag>1</flag></action>
<action method="addJs"><script>mage/adminhtml/variables.js</script></action>
<action method="addJs"><script>mage/adminhtml/wysiwyg/widget.js</script></action>
<action method="addJs"><script>lib/flex.js</script></action>
<action method="addJs"><script>lib/FABridge.js</script></action>
<action method="addJs"><script>mage/adminhtml/flexuploader.js</script></action>
<action method="addJs"><script>mage/adminhtml/browser.js</script></action>
<action method="addJs"><script>prototype/window.js</script></action>
<action method="addItem"><type>js_css</type><name>prototype/windows/themes/default.css</name></action>
<action method="addItem"><type>js_css</type><name>prototype/windows/themes/magento.css</name></action>
</reference>
</default>

Add below code to your form template

<?php 
$_storeBaseUrl = str_replace('index.php', '', Mage::getBaseUrl());
?>
<form >
<button type="button" class="scalable show-hide" style="" id="toggledetails" onclick="hideBlogEditor(this)"><span><span><span>Show / Hide Editor</span></span></span></button>
<textarea name="short_description" title="short_description" id="short_description" class="textarea "  ></textarea>
<script language="javascript" type="text/javascript" src="<?php echo $_storeBaseUrl ?>js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
//< ![CDATA[
Event.observe(window, "load", function() {
tinyMCE.init({
mode : "exact",
theme : "advanced",
width: "100%",
elements : "short_description",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_path_location : "bottom",
extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
theme_advanced_resize_horizontal : "false",
theme_advanced_resizing : "false",
apply_source_formatting : "true",
convert_urls : "false",
force_br_newlines : "true",
doctype : '< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
});
});
 
function showBlogEditor(strItemId){
    strItemId = strItemId.id
    vartheeditor = tinyMCE.get(strItemId); //strItemId is the ID of the HTML element
    if(theeditor&&theteditor.initialized){
        //you can do something here if you need
    }else{
        tinyMCE.execCommand('mceAddControl', false, strItemId);
    }
}
function hideBlogEditor(strItemId){
    if (tinyMCE.getInstanceById(strItemId))
    {
            tinyMCE.execCommand('mceFocus', false, strItemId);
            tinyMCE.execCommand('mceRemoveControl', false, strItemId);
    }           
}
//]]>
</script>
</form>

Magento create frontend editor

Magento create frontend editor

Magento create frontend editor like backend with just few below code

add below code to layout.xml file of module

<default>
<reference name="head">
<action method="setCanLoadExtJs"><flag>1</flag></action>
<action method="addJs"><script>mage/adminhtml/variables.js</script></action>
<action method="addJs"><script>mage/adminhtml/wysiwyg/widget.js</script></action>
<action method="addJs"><script>lib/flex.js</script></action>
<action method="addJs"><script>lib/FABridge.js</script></action>
<action method="addJs"><script>mage/adminhtml/flexuploader.js</script></action>
<action method="addJs"><script>mage/adminhtml/browser.js</script></action>
<action method="addJs"><script>prototype/window.js</script></action>
<action method="addItem"><type>js_css</type><name>prototype/windows/themes/default.css</name></action>
<action method="addItem"><type>js_css</type><name>prototype/windows/themes/magento.css</name></action>
</reference>
</default>

Add below code to your form template

<?php 
$_storeBaseUrl = str_replace('index.php', '', Mage::getBaseUrl());
?>
<form >
<button type="button" class="scalable show-hide" style="" id="toggledetails" onclick="hideBlogEditor(this)"><span><span><span>Show / Hide Editor</span></span></span></button>
<textarea name="short_description" title="short_description" id="short_description" class="textarea "  ></textarea>
<script language="javascript" type="text/javascript" src="<?php echo $_storeBaseUrl ?>js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
//< ![CDATA[
Event.observe(window, "load", function() {
tinyMCE.init({
mode : "exact",
theme : "advanced",
width: "100%",
elements : "short_description",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_path_location : "bottom",
extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
theme_advanced_resize_horizontal : "false",
theme_advanced_resizing : "false",
apply_source_formatting : "true",
convert_urls : "false",
force_br_newlines : "true",
doctype : '< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
});
});
 
function showBlogEditor(strItemId){
    strItemId = strItemId.id
    vartheeditor = tinyMCE.get(strItemId); //strItemId is the ID of the HTML element
    if(theeditor&&theteditor.initialized){
        //you can do something here if you need
    }else{
        tinyMCE.execCommand('mceAddControl', false, strItemId);
    }
}
function hideBlogEditor(strItemId){
    if (tinyMCE.getInstanceById(strItemId))
    {
            tinyMCE.execCommand('mceFocus', false, strItemId);
            tinyMCE.execCommand('mceRemoveControl', false, strItemId);
    }           
}
//]]>
</script>
</form>
June 26, 2015 10:23 pm
image_round

Magento Cookies

Magento Cookies

Magento Cookies : one of key feature of magento that helps to manage frontend and admin section

Here is code to create , edit or delete cookies

<?php 

 Mage::getModel('core/cookie')->set($name, $value, $period, $path, $domain, $secure, $httponly);
/**
 * get cookie with a specific name
 * $name = name of the cookie
 */
 Mage::getModel('core/cookie')->get($name);
 /**
 * get all cookies as an array
 */
 Mage::getModel('core/cookie')->get();
 /**
 * delete/remove cookie
 * $name is mandatory; other parameters are optional and cen be set as null
 */
 Mage::getModel('core/cookie')->delete($name, $path, $domain, $secure, $httponly);

?>

Magento Cookies

Magento Cookies

Magento Cookies : one of key feature of magento that helps to manage frontend and admin section

Here is code to create , edit or delete cookies

<?php 

 Mage::getModel('core/cookie')->set($name, $value, $period, $path, $domain, $secure, $httponly);
/**
 * get cookie with a specific name
 * $name = name of the cookie
 */
 Mage::getModel('core/cookie')->get($name);
 /**
 * get all cookies as an array
 */
 Mage::getModel('core/cookie')->get();
 /**
 * delete/remove cookie
 * $name is mandatory; other parameters are optional and cen be set as null
 */
 Mage::getModel('core/cookie')->delete($name, $path, $domain, $secure, $httponly);

?>
June 26, 2015 10:14 pm
image_round

Magento get Controllername Modulename

Magento get Controllername Modulename

Magento get Controllername Modulename, Actionname and last Routename with below one line code

<?php 

Mage::app()->getRequest()->getControllerName(); // return controller name
 
Mage::app()->getRequest()->getActionName(); // return action name
 
Mage::app()->getRequest()->getRouteName(); // return routes name
 
Mage::app()->getRequest()->getModuleName(); // return module name

?>

Few example as below

if(Mage::app()->getRequest()->getControllerName() == 'category'){
        /* do something */
}

Magento get Controllername Modulename

Magento get Controllername Modulename

Magento get Controllername Modulename, Actionname and last Routename with below one line code

<?php 

Mage::app()->getRequest()->getControllerName(); // return controller name
 
Mage::app()->getRequest()->getActionName(); // return action name
 
Mage::app()->getRequest()->getRouteName(); // return routes name
 
Mage::app()->getRequest()->getModuleName(); // return module name

?>

Few example as below

if(Mage::app()->getRequest()->getControllerName() == 'category'){
        /* do something */
}
June 26, 2015 10:11 pm
image_round

Magento secure urls

Magento secure urls

Magento secure urls : Enable secure url from backend for frontend and for admin

System -> Configuration -> GENERAL -> Web -> Secure -> Use Secure URLs in Frontend = Yes

System -> Configuration -> GENERAL -> Web -> Secure -> Use Secure URLs in Admin = Yes

Get secure url

<?php 
Mage::getBaseUrl('url', $secure = true);
?>

Check if you are on secure url or not with magento code

<?php 
if (Mage::app()->getStore()->isCurrentlySecure()) {
    echo 'Current URL is Secure';
} else {
    echo 'Current URL is NOT Secure';
}

?>

Magento secure urls

Magento secure urls

Magento secure urls : Enable secure url from backend for frontend and for admin

System -> Configuration -> GENERAL -> Web -> Secure -> Use Secure URLs in Frontend = Yes

System -> Configuration -> GENERAL -> Web -> Secure -> Use Secure URLs in Admin = Yes

Get secure url

<?php 
Mage::getBaseUrl('url', $secure = true);
?>

Check if you are on secure url or not with magento code

<?php 
if (Mage::app()->getStore()->isCurrentlySecure()) {
    echo 'Current URL is Secure';
} else {
    echo 'Current URL is NOT Secure';
}

?>
June 26, 2015 10:04 pm
image_round

Magento translate text from frontend

Magento translate text from frontend

Magento translate text from frontend : just follow below steps it will enable translate inline function

1). A much easier alternative to that would be to enable Translate Inline via the Admin Module.
2). After logging into the Admin select System > Configuration
3). Select the Default Store View under Current Configuration Scope.
4). Under the Developer tab enable Translate Inline for Front-end.
5). Save the Configuration and you are done!!
After this click on book icon near to text you want to change. then it will open popup with real text and you will be asked to add your new text

Magento translate text from frontend

Magento translate text from frontend

Magento translate text from frontend : just follow below steps it will enable translate inline function

1). A much easier alternative to that would be to enable Translate Inline via the Admin Module.
2). After logging into the Admin select System > Configuration
3). Select the Default Store View under Current Configuration Scope.
4). Under the Developer tab enable Translate Inline for Front-end.
5). Save the Configuration and you are done!!
After this click on book icon near to text you want to change. then it will open popup with real text and you will be asked to add your new text