
WordPress comes with a simple built-in search you can use on your website, whether you build it with a visual editor or bought a WordPress theme. You enter a search word or phrase, and the search results page shows all relevant pages, posts and so on based on the match.
Ajax offers a more elegant and faster way to search a website – it loads search results without reloading the whole page. In this guide I’ll show you how to create Ajax search without installing another WordPress plugin, using PHP, Ajax and jQuery. Don’t worry if you can’t code. I’ll describe all the code and where to put it so that even a beginner with no programming experience can manage.
The image below this paragraph shows a preview of the finished search from this guide. Thanks to the comments in the code, even an ordinary WordPress user who can’t code can customise some things. Bigger changes, however, require at least some PHP knowledge.

What is Ajax?
AJAX (Asynchronous JavaScript and XML) is a web development technique that lets visitors interact with a web page without reloading the whole page. As a result, the data we request from the server via Ajax loads faster, because the rest of the page (such as the header, footer, ...) doesn’t have to be loaded again.
The benefits of Ajax are fast loading of the requested data and lower server load, since the server has less data to process, which also saves you money you would otherwise pay your web hosting company for more performance. Last but not least, Ajax also contributes to a better user experience on your website.
You can read more about Ajax in WordPress here.
Features of the Ajax search
Because this Ajax search is coded by hand, you can adjust it in any way you need. You won’t be held back by the limited settings of available plugins – you have full control over the code.
- Matches in the title, excerpt and content – After you search for a word/phrase, results are shown based on a full or partial match in the title, excerpt or content of all post types (selected in the code).
- Any post types you like – It’s up to you what the search includes: only pages, posts, products, or everything together. You can choose any post type, including custom post types (CPT).
- Customisable search results – With full control over the code, you decide what appears in the search results. Just the post title, or also a featured image and categories?
- Message while the request is processed – After you search for a word/phrase, a request is sent to the server, which processes it and sends the results back to the client. During this process, the text “Searching...” appears below the search field.

- Callback when there is no match – If there is no relevant match for the search, the text “Nothing found” is displayed.

Custom Ajax search - code and steps
First, create a simple search form containing a text input and a button.
<form action="/" method="get" autocomplete="off">
<input type="text" name="s" autofocus placeholder="Vyhľadať zľavu..." id="keyword" class="input_search"> <!-- vyhľadávacie políčko -->
<button> <!-- Tlačidlo, ktorým zabezpečíte klasické WordPress vyhľadávanie. -->
Hľadať
</button>
</form>
<div class="search_result" id="datafetch"></div> <!-- V tomto div elemente sa zobrazia výsledky vyhľadávania -->You can place this form anywhere on your website. If you build your website with visual editors (page builders) such as Divi Builder, Breakdance, Elementor or Oxygen Builder, you can insert the HTML code using a code block module.
With WordPress themes you usually can’t add HTML code directly, so the best solution is to install a child theme and use a hook to place the HTML code anywhere on the website. Put all the code into the functions.php file of the active child theme. As an alternative to a child theme, you can install the Code Snippets WordPress plugin (free version) and paste all the code there.
TIP! Don’t miss deals on WordPress plugins and WordPress themes.
I styled the search field and results with the following CSS. Feel free to adjust it to your liking.
/* Formulár na vyhľadávanie */
. search_bar form {
Width: 100%;
display: flex;
gap: 10px;
flex-wrap: nowrap;
}
/* Vyhľadávacie políčko */
.search_bar input {
padding: 8px 16px;
width: calc(100% - 80px);
color: #666666;
border: 1px solid #666666;
border-radius: 5px;
outline: none;
}
/* Tlačidlo Hľadať */
.search_bar button {
background-color: white;
padding: 8px 12px;
color: #666666;
border: 1px solid #666666;
border-radius: 5px;
cursor: pointer;
}
.search_bar button:hover {
color: #0a5888;
border-color: #0a5888;
transition-duration: 0.3s;
}
/* Div element, v ktorom sa zobrazia výsledky vyhľadávania */
div.search_result {
display: none;
}
/* UL - zoznam výsledkov */
div.search_result ul {
list-style: none;
padding: 15px;
margin: 0;
}
/* Jednotlivé položky v zozname (výsledky) */
div.search_result ul li {
color: white;
}
/* Jednotlivé výsledky vyhľadávania (napr. jeden článok) */
li.search-result-item {
padding: 10px 0;
border-bottom: 1px solid #666666;
}
/* Odkazy vo výsledkoch vyhľadávania */
li.search-result-item a {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 10px;
color: white;
}
li.search-result-item a:hover {
color: #fd834c;
}Finally, one more step is needed: adding the main part of the code that handles the Ajax call and displays the search results. Paste the following code into the functions.php file in your child theme. As mentioned above, you can alternatively add it via the Code Snippets plugin.
<?php
add_action( 'wp_footer', 'ajax_fetch' ); // Hook, ktorý určuje že kód sa má načítať vo footri
function ajax_fetch() { ?>
<script type="text/javascript">
function debounce(func, delay) { // funkcia, ktorá zabezpečuje odosielanie požiadavky až po 600ms
let timeoutId;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
jQuery("input#keyword").keyup(debounce(function() { // funkcia, ktorá zabezpečuje zobrazenie elementu s výsledkami vyhľadávania po napísaní aspoň 2 písme do inputu
let keyword = jQuery(this).val().toLowerCase();
if (keyword.length > 2) { // podmienka, ktorá zabezpečuje, aby sa požiadavky na server posielali, až keď sú napísané v inpute apsoň dve písmená
jQuery('#datafetch').html('<ul><li>Hľadá sa ...</li></ul>'); // Hláška, ktorá sa zobrazí počas čakania na odpoveď servera
jQuery.ajax({ // ajaxové volanie
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: keyword },
success: function(data) {
jQuery('#datafetch').html(data);
}
});
jQuery("#datafetch").show();
jQuery("#datafetch").css('overflow', 'auto');
jQuery(".search_bar").css('background-color', 'rgba(0,0,0,0.85)');
} else {
jQuery("#datafetch").hide();
jQuery(".search_bar").css('background-color', 'rgba(0,0,0,0.10)');
}
}, 600)); // hodnota, ktorá určuje po akom dlhom čase sa pošle požiadavka na server v milisekundách
</script>
<?php }
// ajax funkcia
add_action('wp_ajax_data_fetch', 'data_fetch'); // endpoint pre prihlásených používateľov
add_action('wp_ajax_nopriv_data_fetch', 'data_fetch'); // endpoint pre neprihlásených používateľov
function data_fetch(){
$the_query = new WP_Query(
array( 'posts_per_page' => -1, // Počet výsledkov vyhľadávania (-1 = všetky relevantné výsledky vyhľadávania)
's' => strtolower(esc_attr( $_POST['keyword'] )),
'post_type' => array('page','post'), // Typy postu medzi ktorými sa bude vyhľadávať
'post_status' => 'publish', // Vyhľadávanie len medzi publikovanými príspevkami
)
);
if( $the_query->have_posts() ) :
echo '<ul>';
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<li class="search-result-item">
<a href="<?php echo esc_url( get_permalink() ); ?>">
<img src="<?php echo get_the_post_thumbnail_url($post_id); ?>" width="87.5px" height="50px"> // Ilustračný obrázok
<div><?php the_title(); ?></div> // Titulok postu
</a>
</li>
<?php endwhile;
echo '</ul>';
else : {
echo '<ul><li>Nič sa nenašlo.</li></ul>'; // Hláška, ktorá sa zobrazí v prípade nulovej zhody
}
wp_reset_postdata();
endif;
die();
}The code above does the following:
- After typing at least 3 letters into the search field and a 600 ms pause after the last character, an asynchronous request is sent to the server. Searching based on one or two letters doesn’t make much sense – the match would be too broad. The 600 ms pause lets you comfortably type the whole word/phrase, so results don’t appear before you’ve finished typing.
- Results from posts and pages are displayed. You can change this depending on what you want to include in the search. In the code 'post_type' => array('page','post') you can change 'page','post' to any post type.
I hope this guide helps you and that this Ajax search makes it easier for visitors to find content on your website.



