Show Static or Category Banner on Product Page – Magento 1.9

ifmagento-1.9product-view

I have the following code in product/view.phtml:

<?php 
    if(Mage::registry('current_category')):
    $_category=Mage::registry('current_category');
    $_helper    = Mage::helper('catalog/output');
        $_imgHtml   = '';
        if ($_imgUrl = $_category->getImageUrl()) {
            $_imgHtml = '<p class="category-image"><img src="'.$_imgUrl.'"     alt="'.$this->escapeHtml($_category->getName()).'" title="'.$this->escapeHtml($_category->getName()).'" /></p>';
            $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
        }?>

    <?php if($_imgUrl) { ?>
    <!-- Category has Image uploaded -->
    <?php echo $_imgHtml ?>
    <?php }else{ ?>
    <!-- Category has NO Image uploaded, show static block -->
    <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('cms_top_banner')->toHtml(); ?>
<?php }?>
<?php endif;?>

This currently shows either the category banner or a static banner if the category does not currently have a banner. However, if I visit the product page directly then no banner is displayed.

Can anyone please suggest an edit to the code so that if a user visits a product directly (i.e. not by visiting a category) then the static banner ('cms_top_banner') will be displayed.

Best Answer

The problem here is, when you are loading your product page directly, Mage::registry('current_category') will return NULL and thus nothing will get executed in your code, since all of your code resides in that parent if loop checking.

You can use below code.

<?php
    $_imgHtml = '';
    $_imgUrl  = false;

    //check whether a valid category exist
    if(Mage::registry('current_category')) {

        //grabing category banner if any
        $_category=Mage::registry('current_category');
        $_helper    = Mage::helper('catalog/output');
        if ($_imgUrl = $_category->getImageUrl()) {

            //prepare banner html
            $_imgHtml = '<p class="category-image"><img src="'.$_imgUrl.'"     alt="'.$this->escapeHtml($_category->getName()).'" title="'.$this->escapeHtml($_category->getName()).'" /></p>';
            $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
        }
    }

    //check a valid image url exist
    if ($_imgUrl) {
            echo $_imgHtml;
    } else {
        echo $this->getLayout()->createBlock('cms/block')
            ->setBlockId('cms_top_banner')
            ->toHtml();
    }
?>

This will make sure, if a valid category does not exist, it will show your default banner in any case.

Related Topic