Monday, November 23, 2009

Link to first product in category, dynamically (for marcfalk)

This is a response for
Problem: Create a link to the first(smallest id) in stock product in a category.
This is the code to retrieve the first product in stock with the smallest id:
(Let's assume the category id you want to do it for is $categoryId)
$_category = Mage::getModel('catalog/category')->load($categoryId);
$collection = Mage::getModel('catalog/product')->getCollection();
"_inventory_table.product_id = e.entity_id",
array('is_in_stock', 'manage_stock')
'(CASE WHEN (((_inventory_table.use_config_manage_stock = 1) AND (_inventory_table.is_in_stock = 1)) OR  ((_inventory_table.use_config_manage_stock = 0) AND (1 - _inventory_table.manage_stock + _inventory_table.is_in_stock >= 1))) THEN 1 ELSE 0 END)',
$collection->getSelect()->order('on_top DESC');
$collection->getSelect()->order('entity_id ASC');
if ($collection->count() > 0){
$_product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($collection->getFirstItem()->getId());
$_product = Mage::getModel('catalog/product');

After that in order to print the product url do this:
<?php if ($_product->getId()) : ?>
<a href="<?php echo $_product->getUrl()?>"> First in stock product in category A  (or <?php echo $_product->getName(); ?>)</a>
<?php endif;?>

In case the category has no products at all the link above will not be displayed.
In case all the products in the category are out of stock the link will point to the product with the smallest id.
if you want in this case not to display the link change the if above into:
<?php if ($_product->getId() && $_product->isSalable()) : ?>


  1. Hello,

    Where do i need to put this code?

    Greetz Peter

  2. Good question Peter.
    I wrote this a long time ago.
    Check this:
    with one minor change. Do not put the code directly in the core file. Properly override the Category model. Here is how: