Pages

Wednesday 31 December 2014

Magento:: checkout as guest enable/disable

By default, in Magento guests can shop without creating a customer account on your site. If you want to, you can disable guest checkout and allow only registered users to purchase products from your store. You can do this from the admin panel of your Magento.

After you log in go to System menu>Configuration>Checkout button in the Sales section on the left>Checkout Options panel on the right. After you expand the Checkout Options panel you'll see a drop-down menu Allow Guest Checkout; just set it to No. Once you do that a drop-down menu will appear under it labeled Require Customer To Be Logged in To Checkout; set it to Yes and click on the Save Config button in the upper right corner.

Tuesday 30 December 2014

Magento:: How to remove all catalog products

Reset all product tables. Beware, below script will delete ALL your product data so do it carefully.


To remove all product go to the database and run the following query
SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_link_type`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;

TRUNCATE TABLE `cataloginventory_stock`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
SET FOREIGN_KEY_CHECKS = 1;
INSERT  INTO `catalog_product_link_type`(`link_type_id`,`code`) VALUES (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
INSERT  INTO `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) VALUES (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
INSERT  INTO `cataloginventory_stock`(`stock_id`,`stock_name`) VALUES (1,'Default');
Note: Then you may require re-indexing all your indexes after running above query.
for that go to System > Index Management > Reindex all.

Magento:: Difference between Mage::getSingleton() and Mage::getModel()

Mage::getSingleton()


Mage::getSingleton() will first check the same class instance is exits or not in memory. If the instance is created then it will return the same object from memory. So Mage::getSingleton() faster then Mage::getModel().
$product1 = Mage::getSingleton('catalog/product');
$product2 = Mage::getSingleton('catalog/product');
$product1 and $product2 both will share same memory of OS and return only one instance each time.

Mage::getgetModel()


Mage::getModel() will create a new instance of an object each time even such object exists in configuration.
$product1 = Mage::getModel('catalog/product');
$product2 = Mage::getModel('catalog/product');
$product1 and $product2 both have different instant of same object and also occupy different memory .

Wednesday 24 December 2014

Magento:: Get Current Url

<?php

     $GetUrl=Mage::helper('core/url')->getCurrentUrl();
     echo "Current Url".$GetUrl;
?>

Tuesday 23 December 2014

Magento:: Get all Cms Pages Link

<?php $collection = Mage::getModel('cms/page')->getCollection()->addStoreFilter(Mage::app()->getStore()->getId());?>

<?php  $collection->getSelect()
->where('is_active = 1'); ?>
<ul id="nav">
<?php foreach ($collection as $page): ?>
<?php $PageData = $page->getData(); ?>
<?php// print_r($PageData);?>
<?php if($PageData['identifier']!='no-route' && $PageData['identifier']!='enable-cookies' && $PageData['identifier']!='home2') { ?>
<li>
<a href="<?php echo $this->getUrl('').$PageData['identifier']?>"><span><?php echo $PageData['title'] ?></span></a>
</li>
<?php } ?>
<?php endforeach; ?>
</ul>

Monday 22 December 2014

Magento:: Custom Login Logout With Email Address

1- For Login Logut
<?php if (! Mage::getSingleton('customer/session')->isLoggedIn()): ?>

   <a href="<?php echo Mage::helper('customer')->getLoginUrl(); ?>" title="Log In" class="login"><?php echo $this->__('Log In') ?></a>
<?php else: ?>
   <a href="<?php echo Mage::helper('customer')->getLogoutUrl(); ?>" title="Log Out" class="login"><?php echo $this->__('Log Out') ?></a>
    <?php endif; ?>
2- For Email Address.

<div class="email">
  <?php  $customer = Mage::getSingleton('customer/session')->getCustomer();
     $customerData = Mage::getModel('customer/customer')->load($customer->getId())->getData();
     $email = $customerData['email'];
     echo $email;
   ?>
</div>

Social Plugin-Facebook

1-Facebook like box
<div id="fb-root"></div>

<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like-box" data-href="https://www.facebook.com/FacebookDevelopers" data-colorscheme="light" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div>
2-Facebook follow button
top script+
<div class="fb-follow" data-href="https://www.facebook.com/zuck" data-colorscheme="light" data-layout="standard" data-show-faces="true"></div>
3-Facebook send message button
top script+
<div class="fb-send" data-href="https://developers.facebook.com/docs/plugins/" data-width="200" data-height="200" data-colorscheme="dark"></div>
4-Facebook share button
top script+
<div class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-width="200"></div>
5- Facebook like share button
top script+
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-width="200" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
6- Facebook comment box
top script+
<div class="fb-comments" data-href="http://example.com/comments" data-numposts="3" data-colorscheme="light"></div>

Tuesday 16 December 2014

Magento:: How To call a static block inside phtml

A static block in phtml file of magento, sometimes we need to do this kind of functionallity. For instance whenever you want to add one banner image on right side of callout block.
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('banner_image_block_id')->toHtml() ?>
banner_image_block_id is the identifier you have created with static block in magento

Magento:: Call .phtml file in cms page

{{block type="core/template" template="custompage/home.phtml"}}
The custompage is a custom folder inside tamplate directory.
and the home.phtml is the file name.

Monday 15 December 2014

Magento:: Popup search box on right sidebar

1-Copy the form.mini.phtml make some changes and create a new file form.mini_popup.phtml as follow:
<div class="search">

<form id="search_mini_form_sidebar" action="<?php echo $catalogSearchHelper->getResultUrl() ?>" method="get">

<div class="form-search_sidebar">

<input id="search_sidebar" type="text" name="<?php echo $catalogSearchHelper->getQueryParamName() ?>" value="<?php echo $catalogSearchHelper->getEscapedQueryText() ?>" class="input-text search_sidebar" maxlength="<?php echo $catalogSearchHelper->getMaxQueryLength();?>" />

<button type="submit" title="<?php echo $this->__('Search') ?>" class="button srch_btn"><span><span><i class="fa fa-search_sidebar"></i></span></span></button>

<i id="searchRemove" title="Close" class="fa fa-times"></i>

<div id="search_autocomplete_sidebar" class="search-autocomplete"></div>

<script type="text/javascript">

//<![CDATA[

var searchForm = new Varien.searchForm('search_mini_form_sidebar', 'search', '<?php echo $this->__('Search entire store here') ?>');

searchForm.initAutocomplete('<?php echo $catalogSearchHelper->getSuggestUrl() ?>', 'search_autocomplete_sidebar');

//]]>

</script>

</div>

</form>

</div>

<script type="text/javascript">

jQuery(window).load(function(){

jQuery(function() {

jQuery('.popup-tool .search').hover(function(){

jQuery('.popup-tool #search_sidebar').animate({

width : '800px'

}, 300 );

jQuery('.popup-tool #search_sidebar').animate({

'marginLeft' : "-=285px" //moves left

});

}, function() {

jQuery('.popup-tool #search_sidebar').animate({width:'580px'}, 300);

jQuery('.popup-tool #search_sidebar').animate({

'marginLeft' : "+=285px" //moves left

});

});

});

});

</script>
2-write down following code in catalogsearch.xml
<block type="core/template" name="top.search_sidebar" as="Search_sidebar" template="catalogsearch/form.mini_popup.phtml"/>
3-call it on header.phtml as follow
getChildHtml('Search_sidebar')?>

Magento:: Minicart on right sidebar


1- First Create a copy of orignal minicart as follow inside the same folder and rename or change the classes
<?php if ($this->getIsNeedToDisplaySideBar()):?>

<div class="sidebar_cart">

<?php

$cart_text='Cart';    

$_cartQty = $this->getSummaryCount() ?>

<div class="block-content_pan">

<div class="summary">

<span class="f-left cart-icon"><i class="fa fa-shopping-cart"></i></span>

<h2 class="classy f-left"><span class="my-cart"><?php echo $this->__('My Cart')?></span>

<?php /*<?php if ($_cartQty==0): ?>

<?php echo $this->__('<a href="%s">0</a><span class="Itext"> %s</span>', $this->getUrl('checkout/cart'), $this->__('item')) ?>

<?php endif ?>

<?php if ($_cartQty>0): ?>

<?php if ($_cartQty==1): ?>

<?php echo $this->__('<a href="%s">1</a><span class="Itext"> %s</span>', $this->getUrl('checkout/cart'), $this->__('item')) ?>

<?php else: ?>

<?php echo $this->__('<a href="%s">%s</a><span class="Itext"> %s</span>', $this->getUrl('checkout/cart'), $_cartQty, $this->__('items')) ?>

<?php endif ?>

<?php endif ?>

*/ ?>

<?php

$count = $this->helper('checkout/cart')->getSummaryCount();  //get total items in cart



if($count==0)

{

echo $this->__('<span class="Itext">0 item</span>',$count)  ;

}

if($count==1)

{

echo $this->__('<span class="Itext">1 item</span>',$count);

}

if($count>1)

{

echo $this->__('<span class="Itext">%s items</span>',$count);

}

?>

</h2>

<!--<em class="bag f-right"><i class="fa fa-angle-down"></i></em>-->

</div>



<div class="remain_cart" id="sidecart" style="display: none;">

<div class="sidecartInner">

<?php if($_cartQty && $this->isPossibleOnepageCheckout()): ?>



<?php endif ?>

<?php $_items = $this->getRecentItems() ?>

<?php if(count($_items)): ?>

<div class="shopping-bag f-block">

<?php if ($_cartQty==1): ?>    

<p class="empty f-left"><?php echo $this->__('Shopping Bag (1 items)') ?></p>

<?php else:?>

<p class="empty f-left"><?php echo $this->__('Shopping Bag (%s items)',$_cartQty) ?></p>

<?php endif?>

<p class="subtotal f-right">

<?php if ($this->canApplyMsrp()): ?>

<span class="map-cart-sidebar-total"><?php echo $this->__('ORDER TOTAL WILL BE DISPLAYED BEFORE YOU SUBMIT THE ORDER');?></span>

<?php else: ?>

<span class="label"><?php echo $this->__('Total:') ?></span> <?php echo Mage::helper('checkout')->formatPrice($this->getSubtotal()) ?>

<?php if ($_subtotalInclTax = $this->getSubtotalInclTax()): ?>

<br />(<?php echo Mage::helper('checkout')->formatPrice($_subtotalInclTax) ?> <?php echo Mage::helper('tax')->getIncExcText(true) ?>)

<?php endif; ?>

<?php endif; ?>

</p>

</div>

<ol id="cart-sidebar" class="mini-products-list">

<?php foreach($_items as $_item): ?>

<?php echo $this->getItemHtml($_item) ?>

<?php endforeach; ?>

</ol>

<script type="text/javascript">decorateList('cart-sidebar', 'none-recursive')</script>

<div class="actions_checkout">

<?php echo $this->getChildHtml('extra_actions') ?>

<button type="button" title="<?php echo $this->__('View Cart') ?>" class="button" onclick="setLocation('<?php echo $this->getUrl('checkout/cart')?>')"><span><span><?php echo $this->__('View Cart') ?></span></span></button>

<button type="button" title="<?php echo $this->__('Checkout') ?>" class="button" onclick="setLocation('<?php echo $this->getCheckoutUrl() ?>')"><span><span><?php echo $this->__('Checkout') ?></span></span></button>

</div>

<?php else: ?>

<div class="shopping-bag f-block"><p class="empty"><?php echo $this->__('You have no items in your shopping cart.') ?></p></div>

<?php endif ?>

</div>

</div>

</div>

</div>

<?php endif;?>

<script type="text/javascript">

jQuery(document).ready(function() {

jQuery(function() {

jQuery(".sidebar_cart").hover(function() {

jQuery(this).addClass('active');

jQuery("#sidecart").stop(true, true).delay(300).slideDown(200, "easeInSine");

},  

function() {

jQuery("#sidecart").stop(true, true).delay(300).fadeOut(100, "easeInCubic");

});



});

});

</script>
2- open the checkout.xml and copy the following block
<block type="checkout/cart_sidebar" name="cart_header" template="checkout/cart/sidebar_header.phtml" after="-">

<action method="addItemRender">

<type>simple</type>

<block>checkout/cart_item_renderer</block>

<template>checkout/cart/sidebar/default.phtml</template>

</action>

<action method="addItemRender">

<type>grouped</type>

<block>checkout/cart_item_renderer_grouped</block>

<template>checkout/cart/sidebar/default.phtml</template>

</action>

<action method="addItemRender">

<type>configurable</type>

<block>checkout/cart_item_renderer_configurable</block>

<template>checkout/cart/sidebar/default.phtml</template>

</action>

<block type="core/text_list" name="cart_sidebar.extra_actions" as="extra_actions" translate="label" module="checkout">

<label>Shopping Cart Sidebar Extra Actions</label>

</block>

</block>
3-Make the following cahanges as follow: and paste it in page.xml inside the block as follow:
<block type="page/html_header" name="header" as="header">

<!--            custom code for minicart                    -->

<block type="checkout/cart_sidebar" name="cart_header" template="checkout/cart/sidebar_cart.phtml" as="sidecart">

<action method="addItemRender">

<type>simple</type>

<block>checkout/cart_item_renderer</block>

<template>checkout/cart/sidebar/default.phtml</template>

</action>

<action method="addItemRender">

<type>grouped</type>

<block>checkout/cart_item_renderer_grouped</block>

<template>checkout/cart/sidebar/default.phtml</template>

</action>

<action method="addItemRender">

<type>configurable</type>

<block>checkout/cart_item_renderer_configurable</block>

<template>checkout/cart/sidebar/default.phtml</template>

</action>

<block type="core/text_list" name="cart_sidebar.extra_actions" as="extra_actions" translate="label" module="checkout">

<label>Shopping Cart Sidebar Extra Actions</label>

</block>

</block>

<!--            custom code for minicart end -->
4-After that call it in header.phtml as follow:
<?php echo $this->getChildHtml('sidecart'); ?>
An example screen of look::

Magento:: Insert a class in foreach loop for every 5th li element

1- Take a variable and assign to 0. like
<?php $counter=0; ?>
2- And give the condition in the li tag as follows.
<li class="product <?php if($counter%5==4): echo "last";  endif;?>"> // for fifth element

Tuesday 9 December 2014

Magento: How to get product stock quantity & other stock information?

Here is a quick code to get any productâ��s stock information like quantity (qty), minimum quantity (min_qty), stock availability (is_in_stock), minimum and maximum sale quantity (min_sale_qty and max_sale_qty), etc.

First load the product. Product can be loaded in different ways. Here are the two different ways to load any product in Magento:-

1. Load product by product ID
$id = 52;

$_product = Mage::getModel('catalog/product')->load($id);
2. Load product by SKU
$sku = "microsoftnatural";

$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
Now, get stock information for the loaded product.
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);
You can check stock data in this way:-
echo "
"; print_r($stock->getData()); echo "
";
Or, you can print individually like this:-
echo $stock->getQty();
echo $stock->getMinQty();
echo $stock->getMinSaleQty();

Magento:: Quantity Box in the Category Products Listing Page

Your Magento product ordering might seem a long process to some business owners, so we thought of making it simple, so that users can directly enter the quantity in the products listing area and click on ADD TO CART and checkout.

So, here is how you can do that.

Goto /app/design/frontend/default/your-theme/template/catalog/product/list.phtml

Open the file on a code editor and find this line,
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
Just replace it with
<form action="<?php echo $this->getAddToCartUrl($_product) ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>

  <?php if(!$_product->isGrouped()): ?>

  <label for="qty"><?php echo $this->__('Qty') ?>:</label>

  <input type="text" name="qty" id="qty" maxlength="12" value="<?php echo ($this->getMinimalQty($_product)?$this->getMinimalQty($_product):1) ?>" />

  <?php endif; ?>

  <button type="button" class="button btn-cart" onClick="this.form.submit()"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>

</form>

Monday 8 December 2014

Remove Trailing Slash From Magento URLs – Duplicate Content Issue

Due to SEO reasons, a common problem that Magento has is that it indexes two URLs of the same page which causes issues with duplicate content when it comes to Google crawling. For example it will index both of these URLs.
http://www.magentosite.com/category.html/
and
http://www.magentosite.com/category.html
Ideally, we would like to stop Magento adding trailing slashes to the end of the URLs and then redirect it to the page without the trailing slash, and here’s how.

Lets begin

To start with we need to edit the getURL() method to stop it generating URLs with trailing slashes, so copy the following file from:
app/code/core/Mage/Core/Block/Abstract.php 
To
app/code/local/Mage/Core/Block/Abstract.php
Now open Abstract.php and find the following line of code:
return $this->_getUrlModel()->getUrl($route, $params);
Replace that line with the following:
$return_url = $this->_getUrlModel()->getUrl($route, $params);

if ($return_url != $this->getBaseUrl() && substr($return_url, -1) == '/' && !Mage::getSingleton('admin/session')->isLoggedIn()):

    return substr($return_url, 0, -1);

else:

    return $return_url;

endif;
Now copy the file app/code/core/Mage/Core/Model/Url.php
to
app/code/local/Mage/Core/Model/Url.php.
Once you’ve done that open it and find the following code:
if ($noSid !== true) {

    $this->_prepareSessionUrl($url);

}
Change ($noSid !== true) to ($noSid == false)

Edit your .HTACCESS file

Find the following line of code:
RewriteRule .* – [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Add the following immediately underneath it:
RewriteCond %{request_method} ^GET$
RewriteCond %{REQUEST_URI} !^/downloader.*$
RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteRule ^(.+)$ %1 [L,R=301]

All done!

 

Magento How to remove index.php from Any URLs in Magento

  1. Go to Magento Dashboard.
  2. Under System->Configuration.
  3. In left menu section under GENERAL tab select web.
  4. under web section open Search Engines Optimization.
  5. And Use Web Server Rewrites option to yes
Example::

Magento:: Non WWW to WWW

Open .htaccess file in Your Root Folder and copy and paste the following code.
#non www to www
RewriteCond %{HTTP_HOST} ^(?!www\.)(.+) [NC]
RewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]

Thursday 4 December 2014

Magento:: Override Core Files – Simplest Way

There are several methods used for overriding magento core files, Here I’m going to explain one of simplest method to override core files in magento.

In this method to override magento core files, you don’t need to create your own module and write some xml in config.xml. Instead you can simply copy core file (which you want to override) and paste it in ‘app/code/local/Mage’ maintaining the same path of that php file. Then you can start editing this file, magento will read your file instead of the core file.
Below is an example :
=> If you would like to override ‘app/code/core/Mage/Catalog/Block/Product.php’ you need simply need it to put Product.php in ‘app/code/local/Mage/Catalog/Block/Product.php’. Doing only this will let magento read this file from local folder instead of core folder.

Reason for such behavior of reading from local folder to core folder is :
This process is called overriding Magento core functionality and is based on the fact that Magento sets its PHP include paths to first look in app/code/local/ then app/code/community/ and finally in app/code/core/. This has the effect that any files of the same name placed under the local or community name space will take precedence in loading, hence, we can override almost any core file in this way.

Demerits of Using Above Approach :

1. For one thing, we must override the complete core file and copy all the class functions. Once the overridden file is in place, this will be the file will be used instead of magento core file always. Given that most core classes contain several and many times a large number of methods it means that we are effectively overriding all those methods in our file.

2. This approach is not magento upgrade friendly, because of the above reasons.

3. This approach doesn’t work for controllers.

This approach is only useful while your testing/developing your module. Instead of writing a whole module, you can quickly override the core class see if things work well.
- See more at: http://excellencemagentoblog.com/blog/2014/03/03/override-magento-core-files-simplest-way/#sthash.6XNrTrxj.dpuf

Magento:: Product Collection with specific ids

<?php

$productIds = array(1,2);

$_productCollection = Mage::getModel('catalog/product')->getCollection();                              

$_productCollection->addAttributeToFilter('status', 1); //enabled

$_productCollection->addAttributeToFilter('visibility', 4); //catalog, search

$_productCollection->addAttributeToFilter('entity_id', array('in' => $productIds));

?>

<?php  

foreach ($_productCollection as $_product)

{

       $model = Mage::getModel('catalog/product');

       $product_id = $_product->getId();

       $_product = $model->load($product_id);

       //echo $_product->getPrice()."";

       //echo $_product->getName()."";

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

       //echo Mage::helper('catalog/image')->init($_image, 'image')."";

       ?>

        <div class="feature-product">

            <div class="feature-product-price"><?php echo $_product->getPrice(); ?></div>

            <div class="feature-product-name"><?php echo $_product->getName(); ?></div>

            <div class="feature-product-image"><a href="<?php echo $_product->getProductUrl() ?>"><img src="<?php echo Mage::helper('catalog/image')->init($_image, 'image')->resize(200,200); ?>"></a></div>

        </div>

   <?php    

}                                       

?>

Tuesday 2 December 2014

Magento Displaying CMS Static Block based on Category ID

1- open developer log to check the listing page layout.
2- In my case i found that it is 3columns.phtml
app/design/frontend/default/your-theme-name/template/page/3columns.phtml
Now in the Magento back end create a new Static Block. I will assume that you are already familiar with creating a Static Block in Magento so will not go into how to do this. If you are not familiar with creating Static Blocks please go to the Magento Knowledge Base
"http://www.magentocommerce.com/knowledge-base/entry/how-do-i-create-and-edit-static-blocks"
Decide where you would like your banner to be displayed in my case after the breadcrumbs then add this code.
<?php $category = Mage::getModel('catalog/layer')->getCurrentCategory();?>
<?php 
$myValidIds = array(3,6);
if(in_array($category->getId(), $myValidIds)):
?>
<?php
echo $this->getLayout()->createBlock('cms/block')->setBlockId('my-sidebar-1')->toHtml();
echo $this->getLayout()->createBlock('cms/block')->setBlockId('my-sidebar-2')->toHtml();
?>
<?php endif; ?>
Firstly you will need to change the numbers in the $myvalidid variable array. Here you will need to add the ID’s of the categories that you would like the Static Block to be visible in separated by comma. Your category ID’s can be found in the Magento back end.
Catalog > Manage Categories
Finally add the identifier for the Static Block you wish to be called into the page.
Save and upload the template file back into your Magento installation.