OpenCart: How to move search field to top menu (content_top.tpl)

Please read this article to learn how to easy move search field to another part of your page. In my case I will move it to my custom menu. First you need to copy the code for the search form from: /catalog/view/theme/-yourtheme-/template/common/header.tpl

Code:

<div id=”search”>
<div class=”button-search”></div>
<?php if ($filter_name) { ?>
<input type=”text” name=”filter_name” value=”<?php echo $filter_name; ?>” />
<?php } else { ?>
<input type=”text” name=”filter_name” value=”<?php echo $text_search; ?>” onclick=”this.value = ”;” onkeydown=”this.style.color = ‘#000000’;” />
<?php } ?>
</div>

Now I will paste this code in my content_top.tpl file located in the same directory as header.tpl

Open up header.php that is located in /catalog/controller/common/ directory
and copy these code lines:

Code:

$this->language->load(‘common/header’);
$this->data[‘text_search’] = $this->language->get(‘text_search’);
if (isset($this->request->get[‘filter_name’])) {
$this->data[‘filter_name’] = $this->request->get[‘filter_name’];
} else {
$this->data[‘filter_name’] = ”;
}

Paste these lines into the file /catalog/controller/common/content_top.php under public function index(). Just paste it below the line 10 or 11.

Copy now language variable for the input search text to the right language file.

Copy variable $_[‘text_search’] = ‘Search’; from /language/-yourlangugage-/common/header.php to /language/-yourlangugage-/yourlanguage.php

The last thing we need to make is to copy js function that will post our search. Your search field is for sure not placed in the #header at this time so we need to copy function from /catalog/view/javascript/common.js and rename it.

Copy and paste this function into the same js file and don’t forget to rename #header according to your div’s/container’s ID (#example) or class (.example).

Code:

$(‘#header input[name=’filter_name’]’).keydown(function(e) {
if (e.keyCode == 13) {
url = $(‘base’).attr(‘href’) + ‘index.php?route=product/search’;
var filter_name = $(‘input[name=’filter_name’]’).attr(‘value’)

if (filter_name) {
url += ‘&filter;_name=’ + encodeURIComponent(filter_name);
}

location = url;
}
});

My div container looks like this <div id=”example”>….search field code…</div> so my javascript function for submitting the search form will look like this:

Code:

$(‘#example input[name=’filter_name’]’).keydown(function(e) {
if (e.keyCode == 13) {
url = $(‘base’).attr(‘href’) + ‘index.php?route=product/search’;
var filter_name = $(‘input[name=’filter_name’]’).attr(‘value’)

if (filter_name) {
url += ‘&filter;_name=’ + encodeURIComponent(filter_name);
}

location = url;
}
});

I hope you enjoyed this article 😉