---
title: "Useful PHP Snippets for Improving WordPress Search"
id: "7581"
type: "post"
slug: "10-useful-wordpress-search-code-snippets"
published_at: "2024-10-19T22:32:24+00:00"
modified_at: "2025-04-22T09:41:06+00:00"
url: "https://speckyboy.com/10-useful-wordpress-search-code-snippets/"
markdown_url: "https://speckyboy.com/10-useful-wordpress-search-code-snippets.md"
excerpt: "We share ten really useful PHP code snippets that will help improve the result accuracy and functionality of search in WordPress."
taxonomy_category:
  - "WordPress"
  - "WordPress Developer"
taxonomy_post_tag:
  - "Code Snippet"
  - "Search UI"
  - "UX Search"
---

# Useful PHP Snippets for Improving WordPress Search

Last Update:  April 22, 2025  
 By  Paul Andrew

[WordPress](https://speckyboy.com/category/wordpress/)
 / [WordPress Developer](https://speckyboy.com/category/wordpress/wordpress-developer/)

It is no secret that the standard search within WordPress is not the greatest. The problem is that WordPress takes your search term far too literally.

In this post, we have ten useful WordPress search code snippets that will help improve the search accuracy for your readers. Just copy and paste.

You might also like these useful [.htaccess snippets & hacks](https://speckyboy.com/useful-htaccess-snippets-and-hacks/)
, these [WordPress SQL Query Snippets](https://speckyboy.com/wordpress-sql-query-snippets/)
, or these snippets that make WordPress [user-friendly for your clients](https://speckyboy.com/20-snippets-and-hacks-to-make-wordpress-user-friendly-for-your-clients/)
.

## How To Exclude Posts or Pages from WordPress Search Results

If you would like to be able to control which posts or pages should be excluded from WordPress search results, all you have to do is copy and paste the code below into your `functions.php` file.

In this snippet, posts with the IDs `0` and `1` will be excluded. Edit accordingly to suit your needs.

```
function SearchFilter($query) {
    if ($query->is_search) {
        $query->set('cat','0,1');
    }
    return $query;
}
add_filter('pre_get_posts','SearchFilter');
```

## WordPress Drop-Down Category Search Form

A useful function you could give to your WordPress search would be to allow your readers to filter the search results by targeting a specific category. This can be achieved by using a simple drop-down containing all of the category titles.

All you have to do is replace the standard WordPress search form (found within the `searchform.php`) with the snippet below:

```
<form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">
  <div>
    <label class="screen-reader-text" for="s">Search for:</label>
    <input type="text" value="" name="s" id="s" /> 
    in <?php wp_dropdown_categories( 'show_option_all=All Categories' ); ?> 
    <input type="submit" id="searchsubmit" value="Search" />
  </div>
</form>
```

## Search Within a Specific WordPress Post Type

WordPress gives you the ability to search specific post types by using this small snippet.

All you have to do is copy and paste the code below into your `functions.php` file.

```
function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  }
  return $query;
}
// This filter will jump into the loop and arrange our results before they're returned
add_filter('pre_get_posts','SearchFilter');
```

## Display the Number of Search Results Returned

If you would like to show your readers how many results have been found per search term, you could use this helpful snippet.

Open `search.php` and locate the following:

```
<h2 class="pagetitle">Search Results</h2>
```

And replace it with this code:

```
<h2 class="pagetitle">Search Result for post_count; _e(''); _e(''); echo $key; _e(''); _e(' &mdash; '); echo $count . ' '; _e('articles'); wp_reset_query(); ?>
```

## Highlight WordPress Search Terms with jQuery

To help make your search results that little bit clearer to your readers, you could use this snippet which will highlight the searched term within the results.

Copy and paste the following code into your theme’s `functions.php` file:

```
function hls_set_query() {
  $query  = attribute_escape(get_search_query());
  if(strlen($query) > 0){
    echo '
      <script type="text/javascript">var hls_query  = "'.$query.'";</script>
    ';
  }
}
function hls_init_jquery() {
  wp_enqueue_script('jquery');
}
add_action('init', 'hls_init_jquery');
add_action('wp_print_scripts', 'hls_set_query');
```

And then add this code into your `header.php` file, just before the `/head` tag:

```
<style type="text/css" media="screen">
    .hls { background: #D3E18A; }
  </style>
  <script type="text/javascript">
  jQuery.fn.extend({
    highlight: function(search, insensitive, hls_class){
      var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g");
      return this.html(this.html().replace(regex, function(a, b, c){
        return (a.charAt(0) == "<") ? a : "<strong class=\""+ hls_class +"\">" + c + "";
      }));
    }
  });
  jQuery(document).ready(function($){
    if(typeof(hls_query) != 'undefined'){
      $("#post-area").highlight(hls_query, 1, "hls");
    }
  });
  </script>
```

## Disable WordPress Search

If you are looking for a way to disable all of WordPress’s search functionality, you could use this small snippet.

All you have to do is copy and paste the code below into your `functions.php` file.

```
function fb_filter_query( $query, $error = true ) {
  if ( is_search() ) {
    $query->is_search = false;
    $query->query_vars[s] = false;
    $query->query[s] = false;

    // to error
    if ( $error == true )
      $query->is_404 = true;
  }
}
add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );
```

## Make your WordPress Search Results Unlimited

Sometimes you may not want your search results to be limited by the confines of the standard WordPress Loop. This snippet allows your search to return unlimited results.

In `search.php` you can add the following code above the loop for this functionality.

First of all find this code within `search.php`:

```
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
```

And then add this code:

```
<?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
```

## Related Articles

- [8 CSS & JavaScript Snippets for Making the Search Field Sexy](https://speckyboy.com/search-field-sexy-css/) From simple CSS enhancements all the way to JavaScript-infused UIs, this collection of snippets will take the humble search field up a notch.
- [How to Fix Common On-Site Search Mistakes](https://speckyboy.com/common-site-search-mistakes-fix/) Your website's search function could be damaging your conversion rates. And if it's not acting as a bane to your conversion rates, it could be…
- [How to Build a Stylish CSS3 Search Box](https://speckyboy.com/how-to-build-a-stylish-css3-search-box/) A search box is probably one of the most common UI elements around, and I think there is no need to explain its purpose anymore.…
- [30+ Best Free Icon Fonts for UI Design](https://speckyboy.com/free-icon-fonts/) We have a collection of the best @font-face icon fonts that you can freely download and use in your next mobile app or web design projects.
- [Using my.WordPress.net to Experiment With AI](https://speckyboy.com/my-wordpress-net-experiment-ai/) Learn how to use my.WordPress.net as a safe AI sandbox. We show you how to install WordPress in the browser, add the AI Assistant app, connect ChatGPT, Claude, or Ollama, and run a few test prompts.

## Related Topics

- [Code Snippet](https://speckyboy.com/topic/code-snippet/)
- [Search UI](https://speckyboy.com/topic/search-ui/)
- [UX Search](https://speckyboy.com/topic/ux-search/)

## Written by Paul Andrew

Paul is the founder and editor of Speckyboy Design Magazine. He has a passion for UI design, print design, motion design, and graphic design, and loves discovering and sharing new resources and templates.

[Read more articles by Paul Andrew](https://speckyboy.com/author/apaulandrew/)

---

Top

This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can [read our Disclosure Policy](https://speckyboy.com/affiliate-disclosure/)
 at any time.
