SearchWP

News

How to Create Custom Search in WordPress Without a Plugin - fea

Wondering how to create a custom search in WordPress without a plugin?

By customizing search on your site, you can increase the number of pageviews, boost your sales, and help your visitors find what they came for faster.

In this article, we’ll talk about how you can customize search on your site without installing a plugin and why you should still consider using a plugin to do that.

Here’s a table of contents to help you quickly navigate through this article:

Let’s begin!

Why is Custom Search Important to Your WordPress Website?

To get started, let’s talk about how a custom search on your site can help you grow your business.

Customizing search on your site allows you to:

  • Deliver more relevant search results. Limit your search to specific categories to narrow your search results and help visitors find what they’re looking for faster.
  • Get more pageviews and sales. Boost your content discoverability and increase your income by promoting specific posts or products in your search results.
  • Build a loyal audience. Visitors who’ve had a positive search experience on your site are more likely to return again to explore more of your content.
  • Drive more traffic from search engines. By helping visitors find the right content faster, you make them stay on your site longer, which is one of the main ranking factors in Google.

After we’ve figured out what benefits custom search can bring to your business, let’s talk about what disadvantages you can expect if you do that without a plugin.

Drawbacks of Creating Custom Search Without A Plugin

You should consider a couple of major drawbacks if you want to create a custom search on your site without a plugin.

1. It Requires Coding Skills and Deep WordPress Knowledge

The main disadvantage of customizing your site search manually is that it requires extensive coding experience and deep knowledge of WordPress.

The thing is, there are no default search configuration tools in WordPress.

Due to that, the only way to customize your search is to modify WordPress core files and the code of your theme.

It’s inconvenient, time-consuming, and unsuitable for non tech-savvy people.

Moreover, if you do something wrong, it can lead to the crash of your site, so you should be very careful when customizing your theme files.

2. You’ll Have Fewer Features

Plus, even if you have extensive coding skills, the number of custom search features you can add without a plugin is limited.

For example, you can’t add multiple search engines with a unique set of rules, exclude specific pages or categories from search, manage the order of your search results, and many more.

So if it’s crucial for you to get complete control over how search works on your site, you should consider using a powerful WordPress search plugin.

3. You May Lose Your Changes

Finally, since customizing search without a plugin requires making edits to your site’s files, you’ll lose all changes you made when you update your theme or WordPress version.

The best way to avoid such situations is to use a WordPress search plugin, as it keeps your settings whatever you do with your site.

With that, let’s take a look at how you can customize search on your site in a few clicks, with no coding needed and regardless of your technical skills.

Easiest Method for Customizing WordPress Search on Your Site

The easiest way to customize a search on your WordPress site is to use a plugin like SearchWP.

SearchWP logo

SearchWP is the top-rated WordPress search plugin trusted by over 30,000 website owners.

Its beginner-friendly interface and powerful features allow you to fully customize your search even if you launch your first website.

For example, with SearchWP, you can manage where WordPress should look for matches, limit search to a specific type of content, enable search by tags and custom fields, and many more.

The best thing is that you can do most of these things in just a few clicks.

You can also use SearchWP to:

  • Show search results in live mode. Enable live display of search results on your site so your visitors can instantly navigate to the content they want.
  • Track searches of your visitors. Collect data on what visitors are searching for on your site, which results are most clickable, and other valuable data.
  • Highlight search terms in search results. Help your visitors figure out if they’ve found the right content faster by highlighting keywords in search results.
  • Exclude specific pages from search. Get rid of clutter in search results on your site by excluding redundant pages and outdated content.

After you learn why SearchWP is the best WordPress search plugin, let’s see how you can use it to customize search on your site for your needs.

Step 1: Install and Activate SearchWP

The first step is to go and grab your copy of SearchWP here.

Once done, go to your SearchWP account dashboard and click Downloads.

go to the Downloads tab

Then, press the Download SearchWP button and save the plugin to your computer.

click Download SearchWP

After downloading, copy your SearchWP license key at the bottom left corner.

copy your license key

Next, you’ll need to install SearchWP on your site. If you need help, you can follow our detailed guide on installing a WordPress plugin.

Once you get SearchWP up and running on your site, the next step is to activate your copy of the plugin.

To do that, go to your WordPress dashboard and click Activate License under the SearchWP button at the top panel.

click Activate License

After that, enter your license key into the License field and press Activate.

press Activate

After you activate your copy of SearchWP, you’re ready to start customizing your search.

Step 2: Start Customizing Your Search

To get started, click Engines in your SearchWP settings.

go to Engines

You can add, remove and customize your search engines on this tab.

your search engines

SearchWP automatically creates the Default search engine after installation.

It’s linked to every existing search form, so by customizing it, you can control how search works across your site.

For example, you can manage the list of your search sources, make WordPress consider new content attributes, limit search to specific categories, and more.

With SearchWP, you can add an unlimited number of search engines and connect them to individual search forms on your site.

Thanks to that, you can quickly create custom search forms for various business needs and place them wherever you want on your site.

Since in this tutorial we want to customize how search works throughout the whole site, we’ll edit the Default search engine.

First, let’s specify where WordPress will search for content by configuring its list of search sources.

Manage Your Search Sources

To get started, press the Sources & Settings button under the Default search engine section.

click Sources and Settings

Here you can manage where WordPress should search for matches. By default, it searches among Posts, Pages, and Media files.

uncheck search sources

To remove a search source, uncheck a box next to it. For example, let’s limit search on our site to posts only.

To do that, we’ll uncheck all other sources except Posts and then click Done to save the changes.

left only Posts search source active

Once we’ve set up our list of search sources, let’s also enhance our search by making WordPress consider post attributes and taxonomies.

Configure Your Search Attributes

To get started, click the Add/Remove Attributes button in the Posts search source section.

click Add Remove attributes

On the appeared window, you can specify attributes and taxonomies you want WordPress to consider when performing a search.

add new attributes

To make a specific custom field searchable, click on the Custom Fields field and enter its name.

click on the Custom Fields field

There is also the Any Meta Key shortcut, by adding which you can make searchable all existing search fields at once.

click Add Any Meta key

When you’re finished adding custom fields, let’s also make WordPress index taxonomies.

In WordPress, taxonomies are a method of classifying content and data. For example, it could be post categories, tags, format, or something else.

To make a new taxonomy searchable, click the Taxonomies field and select the desired taxonomy.

click on the Taxonomies field

For instance, let’s make WordPress consider post tags when performing a search. To do that, choose the Tags option from the drop-down menu.

choose the Tags taxonomy

You can also make WordPress ignore default post attributes such as Title, Content, Slug, and Excerpt by unchecking the boxes next to them.

uncheck the default attributes

After you finish managing the Posts search source attributes, press Done to save the changes.

press Done

Now, let’s see how you can narrow your search to give your visitors more relevant results.

Limit Search to a Specific Post Category

To get started, press the Edit Rules button.

click Edit Rules

Then, click Add Rule.

click Add Rule

Here you can add rules according to which WordPress will filter content in search results.

there are no rules by default

For instance, you can add a rule to exclude specific categories from your search or, vice versa, limit your search to them.

Let’s assume we want to limit search on our test site to the News category.

To do that, first make sure you choose the Only show entries if: option and the Categories taxonomy.

limit search to a specific category

Then enter the name of a category you want to limit your search to in the rightmost field. In our case, it’ll be the News.

specify a category

After you finish customizing the rules of your search engine, click Done to save your changes.

click Done to save your rules

When you’re happy with how you customized your search, you’re ready to move to the final step and save your search engine.

Save Your Search Engine

To do that, press the Save Engines at the upper right corner of your SearchWP dashboard.

click Save Engines

Then click Rebuild Index to make WordPress reindex all of your content and apply the new search engine settings.

click Rebuild Index

That’s it. You’ve fully customized search to your needs without writing a single line of code.

Let’s test your new search to make sure it works according to your customizations.

Step 3: Test Your New Search

To get started, go to your website and perform a test search. For example, since we made post tags searchable, let’s try to find a post by its tags only.

On our test site, we have a post called “New WordPress Features”, which has the “Updates” tag.

Let’s search by this tag and see if we can find our post.

press Find Results

We found the post even though there is no word “updates” in its title, excerpt, or content.

we found the post

It means that our search engine now considers post tags when looking for matches.

Let’s also make sure that search on our site is now limited to the “News” category.

To do that, we’ll search for “WordPress”, since we have many posts related to WordPress in other categories.

make another search

You can see that only posts from the News category are displayed among the search results that we got.

we found the right posts

It means that the rule we added to our search engine, which says that WordPress should only search among the news, works as it should.

So, you’ve just learned the easiest way to customize your search. Now let’s see how you can do it without using a plugin.

Create Custom Search in WordPress Without a Plugin

To customize your search without a plugin, you’ll need to make edits to your theme.

The safest way to do that is to create a child theme of the current theme you’re using on your site.

This way, when you make changes to a child theme, your parent theme remains untouched, allowing you to quickly switch to it in case of critical errors.

Plus, having a child theme allows you to update your parent theme without losing your changes. For more details on how to create a child theme, check out this how to create a child theme tutorial.

After you create and activate a child theme, you’re ready to start customizing your search.

To get started, navigate to Appearance » Theme Files Editor in your WordPress dashboard.

go to Theme Files Editor

Then, find the functions.php file on the right panel and click on it.

click the function file

After that, follow the instructions below depending on what customizations you want to make to search on your site.

Enable Search Posts by Tags and Categories

To make post tags and categories searchable on your site without a plugin, add the following code to your theme’s functions.php file:

/*
 * ----------------------------------------------------------
 *
 * Search Posts by Tags and Categories
 *
 * ----------------------------------------------------------
 */
 
 
/**
 * Join the terms, term_relationship, and term_taxonomy tables.
 *
 * @global $wpdb
 *
 * @param string $join  The JOIN clause.
 * @param object $query The current WP_Query instance.
 *
 * @return string The JOIN clause.
 */
function search_custom_posts_join( $join, $query ) {
 
	global $wpdb;
 
	if ( ! is_main_query() || ! is_search() ) {
		return $join;
	}
 
	$join .= "
    LEFT JOIN
    (
        {$wpdb->term_relationships}
        INNER JOIN
            {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
        INNER JOIN
            {$wpdb->terms} ON {$wpdb->terms}.term_id = {$wpdb->term_taxonomy}.term_id
    )
    ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id ";
 
	return $join;
}
 
add_filter( 'posts_join', 'search_custom_posts_join', 10, 2 );
 
/**
 * Modify the WHERE clause to include searches against taxonomies.
 *
 * @global $wpdb
 *
 * @param string   $where The WHERE clause.
 * @param WP_Query $query The current WP_Query instance.
 *
 * @return string The WHERE clause.
 */
function search_custom_posts_where( $where, $query ) {
 
	global $wpdb;
 
	if ( ! is_main_query() || ! is_search() ) {
		return $where;
	}
 
	// Get additional where clause for the user.
	$user_where = '';
 
	$user_id = get_current_user_id();
	$status  = array( "'publish'" );
 
	// Include private posts if the user is logged in.
	if ( $user_id ) {
		$status[]    = "'private'";
		$user_where .= " AND {$wpdb->posts}.post_author = {$user_id}";
	}
 
	$user_where .= " AND {$wpdb->posts}.post_status IN( " . implode( ',', $status ) . " ) ";
 
	$where .= " OR (
                    {$wpdb->term_taxonomy}.taxonomy IN( 'category', 'post_tag' )
                    AND
                    {$wpdb->terms}.name LIKE '%" . esc_sql( get_query_var( 's' ) ) . "%'
                    {$user_where}
                )";
 
	return $where;
}
 
add_filter( 'posts_where', 'search_custom_posts_where', 10, 2 );
 
/**
 * Set the GROUP BY clause to post IDs.
 *
 * @global $wpdb
 *
 * @param string   $groupby The GROUPBY clause.
 * @param WP_Query $query   The current WP_Query instance.
 *
 * @return string The GROUPBY clause.
 */
function search_custom_posts_groupby( $groupby, $query ) {
 
	global $wpdb;
 
	if ( ! is_main_query() || ! is_search() ) {
		return $groupby;
	}
 
	return "{$wpdb->posts}.ID";
}
 
add_filter( 'posts_groupby', 'search_custom_posts_groupby', 10, 2 );

When you’re finished, press the Update File button to save your changes.

press Done

Now your site visitors can search for posts by tags and categories.

Enable Search by Comment Content and Author Names

To make comments and author names searchable on your site without a plugin, add the following code to your theme’s functions.php file:

/*
 * ----------------------------------------------------------
 *
 * Search by Comment Content and Author Names
 *
 * ----------------------------------------------------------
 */
 
 
/**
 * Joins the comments and posts tables.
 *
 * @global $wpdb
 *
 * @param string $join  The JOIN clause.
 * @param object $query The current WP_Query instance.
 *
 * @return string The JOIN clause.
 */
function search_custom_comments_posts_join( $join, $query ) {
 
	global $wpdb;
 
	if ( ! is_main_query() || ! is_search() ) {
		return $join;
	}
 
	$join .= ' LEFT JOIN ' . $wpdb->comments . ' ON ' . $wpdb->posts . '.ID = ' . $wpdb->comments . '.comment_post_ID ';
 
	return $join;
}
 
add_filter( 'posts_join', 'search_custom_comments_posts_join', 10, 2 );
 
/**
 * Modify the WHERE clause to include searches against comments.
 *
 * @global $wpdb
 *
 * @param string   $where The WHERE clause.
 * @param WP_Query $query The current WP_Query instance.
 *
 * @return string The WHERE clause.
 */
function search_custom_comments_posts_where( $where, $query ) {
 
	global $wpdb;
 
	if ( ! is_main_query() || ! is_search() ) {
		return $where;
	}
 
	$where = preg_replace(
		"/\(\s*" . $wpdb->posts . ".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
		"(" . $wpdb->posts . ".post_title LIKE $1) OR (" . $wpdb->comments . ".comment_author LIKE $1) OR (" . $wpdb->comments . ".comment_content LIKE $1)",
		$where
	);
 
	return $where;
}
 
add_filter( 'posts_where', 'search_custom_comments_posts_where', 10, 2 );
 
/**
 * Prevent search results duplicates.
 *
 * @param string   $distinct The DISTINCT clause.
 * @param WP_Query $query    The current WP_Query instance.
 *
 * @return string The DISTINCT clause.
 */
function search_custom_comments_posts_distinct( $distinct, $query ) {
 
	if ( ! is_main_query() || ! is_search() ) {
		return $distinct;
	}
 
	return 'DISTINCT';
}
 
add_filter( 'posts_distinct', 'search_custom_comments_posts_distinct', 10, 2 );

When you’re done, click the Update File button at the bottom of the editor to save your changes.

click Done

Now your visitors can search by comment content and author names.

Enable Search by Post Custom Fields

To make custom fields searchable on your site without a plugin, add the following code to your theme’s functions.php file:

/*
 * ----------------------------------------------------------
 *
 * Search by Post Custom Fields
 *
 * ----------------------------------------------------------
 */
 
 
/**
 * Joins the postmeta and posts tables.
 *
 * @global $wpdb
 *
 * @param string $join  The JOIN clause.
 * @param object $query The current WP_Query instance.
 *
 * @return string The JOIN clause.
 */
function search_custom_meta_posts_join( $join, $query ) {
 
	global $wpdb;
 
	if ( ! is_main_query() || ! is_search() ) {
		return $join;
	}
 
	$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
 
	return $join;
}
 
add_filter( 'posts_join', 'search_custom_meta_posts_join', 10, 2 );
 
/**
 * Modify the WHERE clause to include searches against postmeta.
 *
 * @global $wpdb
 *
 * @param string   $where The WHERE clause.
 * @param WP_Query $query The current WP_Query instance.
 *
 * @return string The WHERE clause.
 */
function search_custom_meta_posts_where( $where ) {
 
	global $wpdb;
 
	if ( ! is_main_query() || ! is_search() ) {
		return $where;
	}
 
	$where = preg_replace(
		"/\(\s*" . $wpdb->posts . ".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
		"(" . $wpdb->posts . ".post_title LIKE $1) OR (" . $wpdb->postmeta . ".meta_value LIKE $1)", $where );
 
	return $where;
}
 
add_filter( 'posts_where', 'search_custom_meta_posts_where', 10, 2 );
 
/**
 * Prevent search results duplicates.
 *
 * @param string   $distinct The DISTINCT clause.
 * @param WP_Query $query    The current WP_Query instance.
 *
 * @return string The DISTINCT clause.
 */
function search_custom_meta_posts_distinct( $distinct, $query ) {
 
	if ( ! is_main_query() || ! is_search() ) {
		return $distinct;
	}
 
	return 'DISTINCT';
}
 
add_filter( 'posts_distinct', 'search_custom_meta_posts_distinct', 10, 2 );

Once done, press the Update File button at the bottom of the editor to save your changes.

press Done

Now your visitors can search for posts by custom fields.

In this article, you learned how to create a custom search on your site without a plugin and why using a plugin for this goal is much more convenient.

We hope it’ll help you to make a decision and choose which method you prefer to use on your site.

Ready to customize search on your site in a few clicks? You can get started with SearchWP here.

Looking for a way to create a custom theme for your site? Check out our step-by-step tutorial on how to create a custom WordPress theme.

Want to customize your search results page? Follow our how to customize your WordPress search results page guide.

Want to make your search awesome right now?

More than 30,000 sites have chosen SearchWP!

You can utilize all of the content that’s gone unrecognized by native WordPress keyword search instantly with SearchWP.

Get SearchWP for just $99

  • Committed Support
    If you need help, support is fast, friendly, and here for you
  • Streamlined Setup
    Installation and setup that’s optimized for speed
  • Great Documentation
    Helpful, clear, and usable documentation is a priority

See what SearchWP customers have to say

  • “SeachWP is easy to set up and has all the customizing I need to help my clients deliver a better search experience than the native WP search functionality. It also has great analytics that help their content strategy.”

  • “We have a fairly complex network of sites. SearchWP is able to give us all the features we need. Works with Multisite, allows for multiple indexes, works with FacetWP, provides us granular control of results. In addition–fantastic customer service!”

  • “We really love SearchWP. It is properly programmed, does what you expect from it and it’s very flexible. The extensions are a great addition and we often make use of them. Thanks for the great job.”