Thursday 20 October 2016

How to add breadcrumbs on custom phtml page?

You can add breadcrumbs from your custom index controller action. Reference code is below.


<?php 

 
    public function IndexAction() {     
      $this->loadLayout();
      $this->getLayout()->getBlock("head")->setTitle($this->__("CB Magento Developer"));  /* add your page title */
            $breadcrumbs = $this->getLayout()->getBlock("breadcrumbs");
      $breadcrumbs->addCrumb("home", array(
                "label" => $this->__("Home Page"),
                "title" => $this->__("Home Page"),
                "link"  => Mage::getBaseUrl()
           ));

      $breadcrumbs->addCrumb("magento_developer", array(       /* add css class */
                "label" => $this->__("Magento Developer"),
                "title" => $this->__("Magento Developer")
           ));

      $this->renderLayout();

    }


?>

How to call static block in CMS page in admin?

Call static block in CMS Page by following code:



{{block type="cms/block" block_id="your_block_id"}}

Wednesday 19 October 2016

Display Magento Category on any page or custom module page

How you can get list of all categories of your Magento Store.


If you want to display all categories in homepage or any CMS page or any custom module page. There are different ways to get the category listing. Some method are below:-


Get all Categories:

The below code will fetch all categories (both active and inactive), which are added in your Magento Store.


$categories = Mage::getModel('catalog/category')                                         ->getCollection()                                          ->addAttributeToSelect('*');


Get all active categories


The below code will fetch all active categories, which are added in your Magento Store. Thus filtering the inactive categories.


$categories = Mage::getModel('catalog/category')
                    ->getCollection()
                    ->addAttributeToSelect('*')
                    ->addIsActiveFilter();



Get active categories of any particular level


The below code will fetch all active categories of  particular level. Here, I have selected level 2.


$categories = Mage::getModel('catalog/category')->getCollection()
->addIsActiveFilter()
->addAttributeToFilter('level','2')
->addAttributeToSelect('id')
->addAttributeToSelect('name')
->addAttributeToSelect('url_key')
->addAttributeToSelect('url')
->addAttributeToSelect('is_active');


Now, You can display Name, URL, id etc. by following code:


foreach ($categories as $category)
{
        $entity_id = $category->getId();
        $name = $category->getName();
        $url_key = $category->getUrlKey();
        $url_path = $category->getUrl();
}


Monday 17 October 2016

How to add breadcrumbs in Magento.

You have add bredcum by two ways:



1. Via code (Add in a controller):


              $crumbs = Mage::app()->getLayout->getBlock('breadcrumbs');

           $crumbs->addCrumb('home', array(

'label' => 'Home',

'title' => 'Go to Home Page',

'link' => Mage::getUrl('')

));


2. Via Layout XML:


              <reference name="breadcrumbs">

                 <action method="addCrumb">

                     <crumbname>home</crumbname>  <!-- Class Name Which apply on li -->

                    <crumbinfo>

                         <label>Home</label>

                        <title>Go to Home Page</title>

                        <link>/</link>

                  </crumbinfo>

             </action>

            <action method="addCrumb">

 <crumbName>cb</crumbName>  <!-- Class Name Which apply on li -->

<crumbInfo>

<label>CB</label>

<title>CB</title>

</crumbInfo>

  </action>

</reference>


Thursday 13 October 2016

How to import products with custom options by CSV file in Magento

If you want to import products with custom options by CSV file. So, you need some changes in "app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php" file. 

But it is core file of Magento, so we can not change directly in this file.  Because when you update Magento, then this file will be replace from new file and your customization will be removed.

So, you copy this file on same location in "app/code/local" folder.


app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php

 to 

app/code/local/Mage/Catalog/Model/Convert/Adapter/Product.php


Now, open ("app/code/local/Mage/Catalog/Model/Convert/Adapter/Product.php") file and add some following codes.


The below line numbers can change in different Magento versions. I used line numbers according to Magento ver. 1.9.2.4.


At about line 734 you will see:

foreach ($importData as $field => $value) {

Just above add following code:

$custom_options = array();


At about line 742 you will see:

$attribute = $this->getAttribute($field);
if (!$attribute) {
   continue;

}



Now need,  add some code above the continue statement.


/* CUSTOM OPTION CODE */
if(strpos($field,':')!==FALSE && strlen($value)) 
{
$values=explode('|',$value);
if(count($values)>0) 
{
@list($title,$type,$is_required,$sort_order) = explode(':',$field);
$title = ucfirst(str_replace('_',' ',$title));
$custom_options[] = array(
'is_delete'=>0,
'title'=>$title,
'previous_group'=>'',
'previous_type'=>'',
'type'=>$type,
'is_require'=>$is_required,
'sort_order'=>$sort_order,
'values'=>array()
);

foreach($values as $v) 
{
$parts = explode(':',$v);
$title = $parts[0];
if(count($parts)>1) {
$price = $parts[1];
} else {
$price =0;
}
if(count($parts)>2) {
$price_type = $parts[2];
} else {
$price_type = 'fixed';
}
if(count($parts)>3) {
$sku = $parts[3];
} else {
$sku='';
}
if(count($parts)>4) {
$sort_order = $parts[4];
} else {
$sort_order = 0;
}

switch($type) 
{
case 'file':

$custom_options[count($custom_options) - 1]['sku'] = $your_custom_sku;
$custom_options[count($custom_options) - 1]['file_extension'] = $your_custom_file_extension;
$custom_options[count($custom_options) - 1]['image_size_x'] = $your_custom_X_size;
$custom_options[count($custom_options) - 1]['image_size_y'] = $your_custom_Y_size;
$custom_options[count($custom_options) - 1]['price'] = $your_custom_price;
$custom_options[count($custom_options) - 1]['price_type'] = $your_custom_price_type;
break;

case 'field':
case 'area':
$custom_options[count($custom_options) - 1]['max_characters'] = $sort_order;

/* NO BREAK */

case 'date':
case 'date_time':
case 'time':
$custom_options[count($custom_options) - 1]['price_type'] = $price_type;
$custom_options[count($custom_options) - 1]['price'] = $price;
$custom_options[count($custom_options) - 1]['sku'] = $sku;
break;

case 'drop_down':
case 'radio':
case 'checkbox':
case 'multiple':
default:
$custom_options[count($custom_options) - 1]['values'][]=array(
'is_delete'=>0,
'title'=>$title,
'option_type_id'=>-1,
'price_type'=>$price_type,
'price'=>$price,
'sku'=>$sku,
'sort_order'=>$sort_order,
);
break;
}
}
}
}

/* END CUSTOM OPTION CODE */



Now, you'll see $product->save(); . Add following code just after.


/* Remove existing custom options attached to the product */
foreach ($product->getOptions() as $o) 
{
$o->getValueInstance()->deleteValue($o->getId());
$o->deletePrices($o->getId());
$o->deleteTitles($o->getId());
$o->delete();
}

/* Add the custom options specified in the CSV import file */

if(count($custom_options)) 
{
foreach($custom_options as $option) {
try {
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option);
$opt->saveOptions();
}
catch (Exception $e) {}
}

}




That's it. Now, you add all product custom options in CSV file.

For, import a custom option, you have need to add a new column to your CSV import file. The name of the column determines the name and type of the option. The format is: Name:Type:Is Required. 

For example, You want to add drop down option called "Size". So your column header should be Size:drop_down:1 (1 for required, 0 for optional). Here is a list of the Types, which is used for "Custom Options" in the Magento admin area.

* field: Field
* area: Area
* file: File
* drop_down: Drop-down
* radio: Radio Buttons
* checkbox: Checkbox
* multiple: Multiple Select
* date: Date
* date_time: Date & Time
* time: Time

If you want import multiple values for one type (drop_down, radio, checkbox, multiple), so you can specify using a | separator. For Example, you are using Small, Medium, Large Size, you would use "Small|Medium|Large" as the value for the "Size:drop_down:1" column in your csv file.

Here's example of the import product with custom option format:

sku,name,description,price,Size:drop_down:1

T-Shirt1,T-Shirt,A T-Shirt,5.00,Small|Medium|Large
T-Shirt2,T-Shirt2,B T-Shirt,6.00,XS|S|M|L|XL


Now, if you want to an additional price and SKU for each option value. So, the complete syntax with all option values is:

title:price:price_type[fixed or percent]:sku:sort_order

Small|Medium:5:fixed::1|Large:10:percent:L_10:0


Here's the first example with additional price/sku modifiers.

sku,name,description,price,Size:drop_down:1
T-Shirt1,T-Shirt1,A T-Shirt,5.00,Small:0:fixed:-SM:0|Medium:2:percent:-MED:1|Large:3:percent:-LRG:2

Tuesday 12 April 2016

How to get attribute code in Magento filter.phtml file?

If you want to get attribute code in Magento "filter.phtml" file.



Then use below code in foreach loop: 



<?php echo $_item->getFilter()->getAttributeModel()->getAttributeCode() ?>






How to remove product count from layered navigation in Magento?

If we want to remove product count from layered navigation in Magento, then we can follow following different steps:


1. You can disable the product count in layered navigation from the Admin Panel, without modifying any templates.


               Open Admin Panel and change following setting.



System -> Configuration -> Catalog -> Layered Navigation -> Display Product Count   


Set Display Product Count "No" and save setting.






2. You can remove from phtml file.

      Open following file from following location:

      app/design/frontend/base/default/template/catalog/layer


      And Remove below code or comment code:

     (<?php echo $_item->getCount()  ?>)





Thursday 7 April 2016

How to Remove/ Disable “Estimate Shipping and Tax” from cart page in Magento

If You want to Remove or Disable “Estimate Shipping and Tax” from cart page in Magento.


Then remove following code from: 



/app/design/frontend/your_package/yourtheme/layout/checkout.xml



Locate this piece of code on line 89:



<block type="checkout/cart_shipping" name="checkout.cart.shipping" as="shipping" template="checkout/cart/shipping.phtml"/>






Comment it out using <!–.....................…–> like:






Now, refresh the shopping cart page, you will no longer see the ‘Estimate Shipping and Tax’ block.






Tuesday 5 April 2016

How to display “You Save” option on product detail page in Magento

You want to display "You Save: $ 0000" Price for "Special Price" on product detail page in Magento. Then you can follow the following steps:


Copy following file:

   
 app/design/frontend/base/default/template/catalog/product/price.phtml       
    

to your theme folder:


 app/design/frontend/default/yourtemplate/template/catalog/product/price.phtml


Then


Paste Following code, After 

   <?php   else: /* if ($_finalPrice == $_price): */  ?>




Paste Code:


 <?php   if( $cb_finalPrice  <  $cb_OrgPrice ) :     ?>


    <?php 

$_saveDiscountPercent = 100 - round(($cb_finalPrice / $cb_OrgPrice) * 100);  // if you want to display save                                                                           percentage 


  $_saveDiscountAmount = number_format(($cb_OrgPrice - $cb_finalPrice), 2);  


    ?>
        <p class="cbsave">


            <span class="price-label label">You Save :  </span>


            <span class="price">


                   <strong class="save-discont-amount">


 $<?php echo $_saveDiscountAmount ; ?> 


<?php echo '('.$_saveDiscountPercent .'%)'; 

                                   // if you want to display save percentage  ?>


                    </strong> 


            </span>


        </p>


    <?php endif;  ?>





Wednesday 9 March 2016

How we can increase the Magento performance

We can increase the Magento Performance, follow by following steps:


  1. Disable the Magento log
  2. Disable un-used modules
  3. Enable Magento Caching
  4. Enable Gzip compression
  5. Optimize your image
  6. Optimize your Server
  7. Use a Content Delivery Network (CDN)
  8. USE Gzip Components
  9. Put Stylesheets at the Top (CSS Files in head tag)
  10. Put Scripts at the Bottom (Js files in footer)
  11. Avoid CSS Expressions (e.g 100/2)

What are the different features of Magento

  1. User Management
  2. Customer Management
  3. Product Management
  4. Order Management
  5. Payment Management
  6. Site Management
  7. Search engine optimization
  8. International Support


How to change the theme for logged user in Magento

If you want to change Magento Theme for which user is login. Then you can use following code:


<?php


if(Mage::getSingleton('customer/session')->isLoggedIn()):

Mage::getDesign()->setPackageName('your_package_name')->setTheme('your_themename');

        endif;

?>




Wednesday 17 February 2016

How to get total items in cart in Magento

Here is a simple code to get the total products/items in cart in Magento. The below code is return only total products/items count,  did not return total quantity of different products/items. For example - ProductA has 5 quantity in cart and ProductB has 2 quantity in cart then below code return 2 counts because there are total 2 products/items added in cart.



<?php  

$_cartTotalItems = Mage::getSingleton('checkout/cart')->getItemsCount(); 


echo $_cartTotalItems;


?>


Saturday 13 February 2016

How to display products of particular category on Home Page in Magento

If you want to display products of the category on your home page, so first need the category ID. You can easily find category ID from 

Magento Admin Panel -> Catalog -> Manage Categories 




On the Categories page you click on the particular category from the menu on the left and the Category ID will be displayed at the top of the screen(right side). Copy this ID. For example, in the screen above the default category ID is 2.


Now, open the CMS -> Pages. Here, you see all pages list.





Open Home Page and click on Content tab (Left Side).

Paste the following code in text editor: 

{{block type="catalog/product_list" category_id="2" template="catalog/product/list.phtml"}}




You can change the "category_id" according to your requirement.

Now you can save your page and all products of the category will be displayed on your home page.

In case the changes are not displayed on your home page you should clear your Magento Cache from your Admin Panel  

System -> Cache Management 

section.

Now, your products are displaying on Home page. 







How to get category name by category id in Magento

Display category name by category id in Magento.


<?php
     
        $categoryId = 5;      //  Change category id according to you


  // display name and other detail of all category       

  $_category = Mage::getModel('catalog/category')->load($categoryId);



// category name 

echo $categoryName = $_category->getName();
 


// category description 

echo $categoryDescription = $_category->getDescription();

 


// category url 

echo $categoryUrl = $_category->getUrl();

   


// category thumbnail 

echo $categoryThumbnail = $_category->getThumbnail();

 


// category level 

echo $categoryLevel = $_category->getLevel();

 


// parent category

echo $parentCategoryId = $_category->getParentId();


?>








Wednesday 10 February 2016

How to Enable Template/Block Hints in Admin Panel in Magento

If you want to display template path hints in Magento Admin, there is no any setting for display template path hints in Magento Admin. 


But you can do manually in database.


So, Just run this query in Database:



INSERT INTO core_config_data (scope, scope_id, path, value)
VALUES ('default', 0, 'dev/debug/template_hints', 1),
('default', 0, 'dev/debug/template_hints_blocks', 1);




To disable them again, run this query: 


UPDATE core_config_data set value = 0 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints';



UPDATE core_config_data set value = 0 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints_blocks';




To enable again run this query:



UPDATE core_config_data set value = 1 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints';


UPDATE core_config_data set value = 1 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints_blocks';



Here is a screenshot of the Cache Management page with hints turned on:







Saturday 6 February 2016

How to add Scroll To Top button in Magento

Scroll To Top button in Magento


Open your header.phtml file and write below code:


<a href="#" class="scrollToTop">Scroll To Top</a>

<script type="text/javascript">

jQuery(document).ready(function($){
//Check to see if the window is top if not then display button
$(window).scroll(function()

              {
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
}

              else 

               {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top

$('.scrollToTop').click(function() 

              {
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
</script>


Add style code in styles.css file. 


<style>
.scrollToTop{
width:100px;
height:100px;
padding:10px;
text-align:center;
font-weight: bold;
color: #444;
text-decoration: none;
position:fixed;
top:75px;
right:40px;
display:none;
background: url('images/arrow_up.png') no-repeat 0px 20px;
}
.scrollToTop:hover{
text-decoration:none;
}
</style>

Note: Please Download image and upload in image folder. 







How to get Data from post method in Magento

You want to get Data from post method in Magento.


Use following code:



<?php


$arrParams = Mage::app()->getRequest()->getPost();

?>

 

 

Friday 5 February 2016

How to get logged in customer's details by customer's id in Magento

If you want to display customer's details by customer's id in Magento. 


You can use following code:


<?php


  // Check if any customer is logged in or not
if (Mage::getSingleton('customer/session')->isLoggedIn())
{

// Load the customer's data
$customer = Mage::getSingleton('customer/session')->getCustomer();

$id =$customer->getId(); // To get Customer Id


//Get Details Using Customer Id
$customer = Mage::getModel('customer/customer')->load($id)->getData();

                $customer->getName();                  

               $customer->getEmail();

}
?>




Thursday 4 February 2016

How to get logged in customer's details in Magento

If you want to get logged in customer's details in Magento. 


You can use following code:


<?php


  // Check if any customer is logged in or not
if (Mage::getSingleton('customer/session')->isLoggedIn())
{

// Load the customer's data
$customer = Mage::getSingleton('customer/session')->getCustomer();

$customer->getPrefix();
$customer->getName();                    // Full Name
$customer->getFirstname();            // First Name
$customer->getMiddlename();       // Middle Name
$customer->getLastname();           // Last Name
$customer->getSuffix();

// All other customer data
$customer->getWebsiteId();
$customer->getEntityId();
$customer->getEntityTypeId();
$customer->getAttributeSetId();
$customer->getEmail();
$customer->getGroupId();
$customer->getStoreId();
$customer->getCreatedAt();
$customer->getUpdatedAt();
$customer->getIsActive();
$customer->getDisableAutoGroupChange();
$customer->getTaxvat();
$customer->getPasswordHash();
$customer->getCreatedIn();
$customer->getGender();
$customer->getDefaultBilling();
$customer->getDefaultShipping();
$customer->getDob();
$customer->getTaxClassId();
}
?>




Wednesday 3 February 2016

How to get customer name, customer email on order success page in Magento

If you want to display customer name and email on order success page in Magento. 


So use following code on success.phtml page 


(/public_html/app/design/frontend/base/default/template/checkout/success.phtml)




<?php


 $order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());


      echo $order->getCustomerName();


      echo $order->getCustomerEmail();


?>




How to get custom attribute value in Magento

Display custom attribute value in Magento


When we get custom attribute value in Magento through simple way like:



<?php 


echo $_product->getAttributeText('custom_attribute_code');


?>


Then we will get a fatal error (as following) , if the custom attribute is not already added. 


" Fatal error: Call to a member function getSource() on a non-object in ...\app\code\core\Mage\Catalog\Model\Product.php on line 1388"


So we will use following code for get custom attribute value in Magento.

The following code will first check that the custom attribute are added or not in admin. If custom attribute are added then get its value.




<?php 

$attribute = $_product->getResource()->getAttribute('custom_attribute_code');

         if ($attribute)

          {

               echo $attribute_value = $attribute ->getFrontend()->getValue($_product);

          }

?>




Saturday 30 January 2016

How to get Review/Rating summary in Magento

We can use the below code to retrieve product Review/Rating summary in Magento



<?php 


$product = Mage::getModel('catalog/product')->load($productId);


$storeId    = Mage::app()->getStore()->getId();


$summaryReview = Mage::getModel('review/review_summary')
  ->setStoreId($storeId)
  ->load('product_id');


  if($summaryReview->getRatingSummary()){


  ?>


  <div class="rating-box" style="float:left;">


<div class="rating" style="width: <?php echo $summaryData->getRatingSummary().'%'; ?>">

                             </div>
  </div>
<?php 
}
?>

How to display category name by product id in Magento

If you want to get Category Name by Product Id in Magento. Use following code:



<?php 

$product = Mage::getModel('catalog/product')->load($_product->getId());


$cat_id = $product->getCategoryIds();


foreach($cat_id as $categorycbId) {


$category_id = Mage::getModel('catalog/category')->load($categorycbId);


echo $category_id->getName();


}

?>


Friday 29 January 2016

How to display static block with title in phtml file : Magento

If you want to display static block in PHTML file in Magento. We can use following code:


<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('identifier')->toHtml() ?>



But If you want to display static block with title. So, we can you following code:


<?php
     $block = Mage::getModel('cms/block')--->load('identifier');
     echo $block->getTitle();
     echo $block->getContent();
?>