Page Ranking Tool

Add Search By Category In Advanced Search In Magento

Magento has its very powerfull search functionality, you can includes all the filters (Attributes) in it from the admin panel or can remove the unused attributes through the admin panel. But in Magento the advanced search page, “search by category” is not an by default option. Suppose you wants to add the “Search By Category” options in Magento Advance search, by using the given below tutorial its very easy to implement it.

Step 1. Required files in which we have to edit the code

app/code/core/Mage/CatalogSearch/Block/Advanced/Form.php
app/code/core/Mage/CatalogSearch/Model/Advanced.php
app/design/yourdesign/yourdesign/template/catalogsearch/advanced/form.phtml

Step 2. Navigate to the app/code/core/Mage/CatalogSearch/Block/Advanced/Form.php and open the file in the editor of your choice and add the below code very end of the file before closing the brace.

public function getStoreCategories()
{
$helper = Mage::helper('catalog/category');
return $helper->getStoreCategories();
}

Step 3.  Now navigate to the app/code/core/Mage/CatalogSearch/Model/Advanced.php, open the file in the editor of your choice and search for the getSearchCriterias() function and replace the getSearchCriterias() with the code below.

public function getSearchCriterias()
{
$search = $this->_searchCriterias;
/* for displaying the category filter */
if(isset($_GET['category']) && is_numeric($_GET['category'])) {
$category = Mage::getModel('catalog/category')->load($_GET['category']);
$search[] = array('name'=>'Category','value'=>$category->getName());
}
return $search;
}

and search for the getProductCollection(); function in the same file and replace the getProductCollection(); function with the code below.


public function getProductCollection(){
if (is_null($this->_productCollection)) {
$this->_productCollection = Mage::getResourceModel('catalogsearch/advanced_collection')
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addMinimalPrice()
->addStoreFilter();
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($this->_productCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($this->_productCollection);
/* adding category filter */
if(isset($_GET['category']) && is_numeric($_GET['category'])) $this->_productCollection->addCategoryFilter(Mage::getModel('catalog/category')->load($_GET['category']),true);
}

return $this->_productCollection;
}

Step 3. Adding the Category dropdown for the frontend.

Now we have to display all the categories into the Advance Search from there user can select the Categories. For this navigate to the file app/design/frontend/default/your_custom_theme/template/catalogsearch/advanced/form.phtml or you can find this file app/design/frontend/base/default/template/catalogsearch/advanced/form.phtml search for the below code.

<ul id="advanced-search-list">
<?php foreach ($this->getSearchableAttributes() as $_attribute): ?>
<?php $_code = $_attribute->getAttributeCode() ?>
<li>
<label for="<?php echo $_code ?>"><?php echo $this->getAttributeLabel($_attribute) ?></label>
<?php switch($this->getAttributeInputType($_attribute)):
case 'number': ?>
<div>
<input name="<?php echo $_code ?>[from]" value="<?php echo $this->htmlEscape($this->getAttributeValue($_attribute, 'from')) ?>" id="<?php echo $_code ?>" title="<?php echo $this->htmlEscape($this->getAttributeLabel($_attribute)) ?>"  type="text" />
<input name="<?php echo $_code ?>[to]" value="<?php echo $this->htmlEscape($this->getAttributeValue($_attribute, 'to')) ?>" id="<?php echo $_code ?>_to" title="<?php echo $this->htmlEscape($this->getAttributeLabel($_attribute)) ?>"  type="text"/>
</div>
<?php break;
case 'select': ?>
<?php echo $this->getAttributeSelectElement($_attribute) ?>
<?php break;
case 'yesno': ?>
<?php echo $this->getAttributeYesNoElement($_attribute) ?>
<?php break;
case 'date': ?>
<?php echo $this->getDateInput($_attribute, 'from') ?>
-
<?php echo $this->getDateInput($_attribute, 'to') ?>
<?php break;
default: ?>
<input name="<?php echo $_code ?>" id="<?php echo $_code ?>" value="<?php echo $this->htmlEscape($this->getAttributeValue($_attribute)) ?>" title="<?php echo $this->htmlEscape($this->getAttributeLabel($_attribute)) ?>"  type="text" />
<?php endswitch; ?>
</li>
<?php endforeach; ?>
</ul>

and Add this code below the above code but remember that it should be under the </ul> tag.

<li>
<label for="category_search_field">Search by Category:</label>
<select name="category" id="category_search_field">
<option value="">-- Select Category --</option>
<?php foreach ($this->getStoreCategories() as $_category): ?>
<?php if($_category->hasChildren()): ?>
<option value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>
<?php foreach ($_category->getChildren() as $subcategory):
if($subcategory->getIsActive()) : ?>
<option value="<?php echo $subcategory->getId(); ?>"<?php echo ($this->getRequest()->getQuery('category') == $subcategory->getId() ? ' selected="selected"': "") ?>><?php echo $subcategory->getName(); ?></option>
<?php endif; endforeach; ?>
<?php elseif($_category->getIsActive()): ?>
<option value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>
<?php endif; ?>
<?php endforeach ?>

</select>
</li>

Then the code will look like as the below.

<ul id="advanced-search-list">
<?php foreach ($this->getSearchableAttributes() as $_attribute): ?>
<?php $_code = $_attribute->getAttributeCode() ?>
<li>
<label for="<?php echo $_code ?>"><?php echo $this->getAttributeLabel($_attribute) ?></label>
<?php switch($this->getAttributeInputType($_attribute)):
case 'number': ?>
<div>
<input type="text" name="<?php echo $_code ?>[from]" value="<?php echo $this->escapeHtml($this->getAttributeValue($_attribute, 'from')) ?>" id="<?php echo $_code ?>" title="<?php echo $this->escapeHtml($this->getAttributeLabel($_attribute)) ?>" maxlength="<?php echo $maxQueryLength;?>" />
<span>-</span>
<input type="text" name="<?php echo $_code ?>[to]" value="<?php echo $this->escapeHtml($this->getAttributeValue($_attribute, 'to')) ?>" id="<?php echo $_code ?>_to" title="<?php echo $this->escapeHtml($this->getAttributeLabel($_attribute)) ?>" maxlength="<?php echo $maxQueryLength;?>" />
</div>
<?php break;
case 'price': ?>
<div>
<input name="<?php echo $_code ?>[from]" value="<?php echo $this->escapeHtml($this->getAttributeValue($_attribute, 'from')) ?>" id="<?php echo $_code ?>" title="<?php echo $this->escapeHtml($this->getAttributeLabel($_attribute)) ?>"  type="text" maxlength="<?php echo $maxQueryLength;?>" />
<span>-</span>
<input name="<?php echo $_code ?>[to]" value="<?php echo $this->escapeHtml($this->getAttributeValue($_attribute, 'to')) ?>" id="<?php echo $_code ?>_to" title="<?php echo $this->escapeHtml($this->getAttributeLabel($_attribute)) ?>"  type="text" maxlength="<?php echo $maxQueryLength;?>" />
<small>(<?php echo $this->getCurrency($_attribute); ?>)</small>
</div>
<?php break;
case 'select': ?>
<div>
<?php echo $this->getAttributeSelectElement($_attribute) ?>
</div>
<?php break;
case 'yesno': ?>
<?php echo $this->getAttributeYesNoElement($_attribute) ?>
<?php break;
case 'date': ?>
<div>
<?php echo $this->getDateInput($_attribute, 'from') ?>
<span>-</span>
<?php echo $this->getDateInput($_attribute, 'to') ?>
</div>
<?php break;
default: ?>
<div>
<input type="text" name="<?php echo $_code ?>" id="<?php echo $_code ?>" value="<?php echo $this->escapeHtml($this->getAttributeValue($_attribute)) ?>" title="<?php echo $this->escapeHtml($this->getAttributeLabel($_attribute)) ?>"  maxlength="<?php echo $maxQueryLength;?>" />
</div>
<?php endswitch; ?>
</li>
<?php endforeach; ?>

<!---Category Code Starts Here------>

<li>
<label for="category_search_field">Search by Category:</label>
<select name="category" id="category_search_field">
<option value="">-- Select Category --</option>
<?php foreach ($this->getStoreCategories() as $_category): ?>
<?php if($_category->hasChildren()): ?>
<option value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>
<?php foreach ($_category->getChildren() as $subcategory):
if($subcategory->getIsActive()) : ?>
<option value="<?php echo $subcategory->getId(); ?>"<?php echo ($this->getRequest()->getQuery('category') == $subcategory->getId() ? ' selected="selected"': "") ?>><?php echo $subcategory->getName(); ?></option>
<?php endif; endforeach; ?>
<?php elseif($_category->getIsActive()): ?>
<option value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>
<?php endif; ?>
<?php endforeach ?>

</select>
</li>

<!---Category Code Ends------------->

</ul>

Step 4. Now Navigate to the app/code/core/Mage/CatalogSearch/Model/Advanced.php and open the file in the editor of your choice and search for the addFilters() function and you will see the following codes, replace this one

if ($allConditions) {
$this->getProductCollection()->addFieldsToFilter($allConditions);
} else if (!count($filteredAttributes)) {
Mage::throwException(Mage::helper('catalogsearch')->__('You have to specify at least one search term'));
}

with the below codes.

if (($allConditions) || (isset($values['category']) && is_numeric($values['category']))) {
$this->getProductCollection()->addFieldsToFilter($allConditions);
} else if (!count($filteredAttributes)) {
Mage::throwException(Mage::helper('catalogsearch')->__('You have to specify at least one search term'));
}

Now it is done and it will look like as the image below.

Comments
  1. Carson

    I alωays useԁ to stuԁу pаragraph in
    news ρapeгѕ but noω aѕ I am a uѕег of net thus fгom
    now I am using net foг ρosts, thankѕ to web.

  2. hidden security camera system

    Nice post. I was checking continuously this blog and I am impressed!

    Very useful info specially the last part 🙂 I care for such information much. I was
    looking for this particular info for a long
    time. Thank you and best of luck.

  3. bestanalyticsconsultants

    Thanκs designed fοr sharing such a
    nice іdеa, ρieсe of writing іs nice, thatѕ why i haνe rеad
    іt fully

  4. analytics consultant

    Mаgnificent bеаt ! І would like tο appгenticе
    while yоu amend youг sitе, hοw could i subscribe fοr а blоg web sitе?
    The аccount helpeԁ me a acсeptablе dеal.
    I had bеen a little bit acquаinted of
    this your broadсast proѵided bright clear iԁea

  5. Michell

    I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored subject matter stylish.

  6. dfw taxi

    My bгothеr suggеsted I might lіke this
    website. He used to bе entiгely rіght.
    Thіѕ submit actuаlly maԁе my
    day. You cann’t believe just how so much time I had spent for this information! Thanks!

  7. Ι’m really inspired along with your writing skills as smartly as with the structure in your weblog. Is this a paid subject matter or did you modify it yourself? Either way keep up the nice high quality writing, it’s rare to ѕee a great wеblog liκe this one nowadаyѕ.

  8. Hellο, alωаys i used tο сheck web ѕіte pоѕtѕ heгe in thе еarly hours in the morning, bеcause i enјоy to learn morе and more.

    Vіsit mу web site: timothy hay for rabbits

  9. benniebaldridge

    You really make it seem so easy with your presentation but I find this matter to be actually something that I
    think I would never understand. It seems too complex and extremely broad for me.
    I am looking forward for your next post, I’ll try to get the hang of it!

  10. Nannette

    My brother recommended I might like this web site.
    He was once totally right. This submit truly made
    my day. You can not consider simply how so much time I had spent for this info!

    Thanks!

  11. domeni

    Thanks for any other informative web site.
    Where else may I am getting that type of information
    written in such a perfect manner? I’ve a mission that I’m just now working on, and I have been
    at the look out for such information.

  12. tanisha

    Admiring the commitment you put into your blog and
    in depth information you present. It’s awesome to come across a blog every once in a while that isn’t the
    same unwanted rehashed information. Excellent
    read! I’ve bookmarked your site and I’m including your
    RSS feeds to my Google account.

  13. rich.slocum

    What’s Taking place i’m new to this, I stumbled upon this
    I have found It absolutely helpful and it has aided me out loads.
    I hope to contribute & help different users like its helped
    me. Great job.

  14. Michael Kors

    discussion concerning this paragraph here at this webpage,
    I have read all that, so now me also commenting at this place.|
    I am sure this piece of writing has touched all the internet visitors, its really really good post on building
    up new website.|
    Wow, this post is nice, my sister is analyzing these kinds of things, thus
    I am going to tell her.|
    bookmarked!!, I love your website!|
    Way cool! Some very valid points! I appreciate you

  15. Lukas

    Its like you read my mind! You seem to know so much about this, like you wrote the book
    in it or something. I think that you can do with some pics to drive the message
    home a little bit, but instead of that, this is magnificent blog.

    A fantastic read. I will certainly be back.

  16. juankirtley

    Heya exceptional blog! Does running a blog similar to this take a large amount of work?
    I’ve absolutely no understanding of programming however I had been hoping to start my own blog soon.
    Anyhow, if you have any recommendations or tips for new blog owners please share.
    I know this is off subject but I simply wanted to ask.

    Appreciate it!

  17. Bern

    conversation concerning this article at this place at this web site, I have read all that,
    so at this time me also commenting at this place.
    I am sure this paragraph has touched all the internet viewers, its really really
    nice paragraph on building up new blog.
    Wow, this piece of writing is fastidious, my younger sister is analyzing these things, so I am
    going to inform her.
    Saved as a favorite, I love your web site!
    Way cool! Some very valid points! I appreciate you

  18. jake

    I have been surfing on-line greater than three hours as of
    late, but I by no means found any interesting
    article like yours. It’s beautiful value enough for me. Personally, if all web owners and bloggers made
    good content as you probably did, the internet will be much more useful than ever before.

  19. Paul

    bookmarked!!, I love your site!

  20. Laylabeatty

    Fantastic goods from you, man. I’ve understand your stuff previous to and you’re
    just extremely great. I actually like what you
    have acquired here, certainly like what you’re saying and the way
    in which you say it. You make it enjoyable and you still
    care for to keep it smart. I can not wait to read far more from you.
    This is actually a wonderful website. wlan repeater test

  21. Rogelio

    I have been browsing online greater than 3 hours lately, yet I
    never discovered any fascinating article like yours.
    It is lovely price enough for me. In my view, if all site owners and bloggers made good
    content material as you did, the web might be a lot more useful than ever before.

  22. Larry

    Excellent post. I’m facing some of these issues as
    well..

  23. prince

    Hi there colleagues, its wonderful article about tutoringand entirely
    explained, keep it up all the time.

  24. nitesh

    Hi,
    i follow your step and i have issue when a search only by category then it give error ‘Please specify at least one search term.’ but when i search category with other available option it works fine.

    plz have look
    thanks

ADD YOUR COMMENT

*