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(); 
    $ids = $treeModel->getCollection()->getAllIds(); 
    $data = array();
    if (!empty($ids))
        foreach ($ids as $id)
            $cat = Mage::getModel('catalog/category'); 
            $categoryData = array('id'=>$cat->getId(),
                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/

After that add below code-

<select id="category" class="search_select" name="cat">
           <option value="">category</option>
           $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>

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

That's it.