Magento – How to get first product from category in 1column.phtml

categorycategory-attributemagento-1.9

I'm searching for a way to get the main image from the first (or random) product from the current category and use it as a background for the category title.

As the title is created in 1column.phtml (or 2columns-left.phtml, 2columns-right.phtml, 3columns.phtml), the code should work there. I've tried all different solutions from this post, but it just gives me errors.

According to the code in 1column.phtml I've tried to get something like this as a first step inside :

<header class="page-header">
    <div class="container">...</div>
</header>

 

<?php if (Mage::app()->getFrontController()->getRequest()->getControllerName() == 'category') : ?>
<h1 class="title"><?php echo $_category->name ?></h1>
<?php echo $_category->getProductCollection()->getFirstItem()->getName(); ?>
<?php endif; ?>

This was an attempt that doesn't give back errors, but has no output at all. I'm pretty sure there is a was, but I'm clueless how to call anything useful within 1column.phtml.

Best Answer

Please use registry variable for this case.

<?php if (Mage::app()->getFrontController()->getRequest()->getControllerName() == 'category') : 
    if ($_category = Mage::registry('current_category')) :
        $_helper    = Mage::helper('catalog/output');
?>
        <h1 class="title"><?php echo $_helper->categoryAttribute($_category, $_category->getName(), 'name') ?></h1>
        <?php echo $_category->getProductCollection()->getFirstItem()->getName(); ?>
    <?php endif; ?>
<?php endif ;?>