Magento: How to search by category in top search

In this article I'll discuss about the search section of magento. If you want to add category search drop down in search section in header part then you have to follow below steps for adding category drop down list in search form.

First of all, How to get all categories-

function get_categories()
{
    $category = Mage::getModel('catalog/category'); 
    $treeModel = $category->getTreeModel(); 
    $treeModel->load();
     
    $ids = $treeModel->getCollection()->getAllIds(); 
     
    $data = array();
     
    if (!empty($ids))
    { 
        foreach ($ids as $id)
        { 
            $cat = Mage::getModel('catalog/category'); 
            $cat->load($id); 
            $categoryData = array('id'=>$cat->getId(),
                              'url'=>$cat->getUrl(),
                              'name'=>$cat->getName(),
                              'image'=>$cat->getImageUrl(),
                              'isActive'=>$cat->getIsActive()
                             );
            if($id>2)
            {
                array_push($data, $categoryData);
            } 
        } 
    }
     
    return $data;
}

This function will return all categories, you can adjust it if you need.

Add the below code in the app/design/frontend/default//template/catalogsearch/form.mini.phtml

After that add below code-

<select id="category" class="search_select" name="cat">
           <option value="">category</option>
           <?php 
           $categories = get_categories();
           #echo '<pre/>';print_r($categories);exit;
           foreach($categories as $k=>$v) 
           {
           ?>
           <option value="<?php echo $v['id']; ?>" <?php echo  (isset($_GET['cat']) && isset($_GET['q']) && $_GET['cat'] == $v['id'] )? 'selected':''; ?>><?php echo $v['name']; ?></option>
           <?php 
           } 
           ?>
       </select>

The select tag need to have the name = "cat".

That's it.