Including Custom Field Values in WordPress Search

- Advertisement -

How to Include Custom Field Values in WordPress Search

By default, WordPress search works by searching post content and titles. However, if you have an advanced website where data is stored in custom fields, you may want to also search those values. In this guide, we will provide you with the code needed to update WordPress so it can search custom fields, all without the need for a third-party plugin.

- Advertisement -

If you are not a developer or are hesitant to add custom code to your website, we would recommend using a third-party plugin such as SearchWP or Relevanssi. Both of these plugins are completely free but offer premium upgrades.

Cautionary note: The code provided in this tutorial will make it so WordPress will use ALL custom field values in the search calculation. Depending on your site, this could create a security concern or slow down your search queries.

- Advertisement -

Table of Contents
1. Why Search Custom Fields
2. How to Search by Custom Fields without a Plugin
2.1 Step 1: Filter the JOIN Clause
2.2 Step 2: Filter the WHERE Clause
2.3 Step 3: Filter the DISTINCT Clause (optional)
3. PHP Class & Plugin
4. Conclusion

Why Search Custom Fields

- Advertisement -

We previously wrote an article on Why & How to Improve the Internal WordPress Site Search. This article goes over the reasons why you may want to improve the WordPress site search and which plugins are good for the job. Instead of reiterating everything here, we recommend checking out that post.

That said, let’s consider an example of a website that has a post type for the organization’s staff members. For staff members, you will likely have custom fields to store data such as their job title, skills, education, etc. Therefore, you may want to include these fields in the WordPress search calculation to make it easier to locate members.

However, before modifying how the WordPress search works, take a moment to think if you really need to. There are situations where modifying your search results won’t provide the best user experience. It may be better to create an AJAX filter so users can select values from various fields to limit the posts by.

How to Search by Custom Fields without a Plugin

In order to allow custom field values to be included in WordPress search results, we will need to hook into three different filters (one optional). We’ll filter the JOIN, WHERE, and DISTINCT clauses for the search query. Let’s walk through each filter and explain what it’s doing.

Step 1: Filter the JOIN Clause

We’ll start by modifying the JOIN clause via the posts_join filter.

“`php
/**
* Adds the postmeta table to the search query.
*/
function wpexplorer_filter_search_join( $join, $query ) {
if ( $query->is_search() ) {
global $wpdb;
$join .= ” LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id”;
}
return $join;
}
add_filter( ‘posts_join’, ‘wpexplorer_filter_search_join’, 10, 2 );
“`

By default, WordPress is set up to search only the “posts” table, and since custom fields are stored inside their own “postmeta” table, we’ll need to include it in the query. That’s what the previous snippet does.

Step 2: Filter the WHERE Clause

Next, we’ll filter the WHERE clause by hooking into the posts_where hook.

“`php
/**
* Adds meta values to the search query.
*/
function wpexplorer_filter_search_where_clause( $where, $query ) {
if ( $query->is_search() ) {
global $wpdb;
$where = preg_replace(
“/(s*{$wpdb->posts}.post_titles+LIKEs*(‘[^’]+’)s*)/”,
“({$wpdb->posts}.post_title LIKE $1) OR ({$wpdb->postmeta}.meta_value LIKE $1)”,
$where
);
}
return $where;
}
add_filter( ‘posts_where’, ‘wpexplorer_filter_search_where_clause’, 10, 2 );
“`

The previous code tells the WordPress search query to look inside the meta_value columns. Again, this will include all custom fields. If you only want WordPress to search specific fields, the code will be much more complex.

Step 3: Filter the DISTINCT Clause (optional)

Lastly, we’ll filter the posts_distinct hook.

“`php
/**
* Prevent duplicate posts in search results.
*/
function wpexplorer_filter_posts_distinct( $where, $query ) {
if ( $query->is_search() ) {
return “DISTINCT”;
}
return $where;
}
add_filter( ‘posts_distinct’, ‘wpexplorer_filter_posts_distinct’, 10, 2 );
“`

This last bit of code prevents duplicate search results if you have custom fields with the same values added to the same post in different fields. This isn’t generally an issue, but it’s worth mentioning. It doesn’t hurt to add the code regardless.

PHP Class & Plugin

To make it easier, we’ve compiled all three snippets above into a single class that you can add to your site. Using a class will keep the code separate and neatly organized. You can add the code to your child theme’s functions.php file or a code snippet plugin.

We recommend adding the PHP class inside its own file in your child theme and loading it using require. This will keep your code nicely organized instead of having a massive functions.php.

Conclusion

As you can see, including custom field values in the internal WordPress search is easy. There may be situations where it is useful, such as searching for staff members on a website. Let us know in the comments if you have any issues or questions, and also why you are adding the code to your site. We would be curious to see some real-world examples.

- Advertisement -

Related articles

4 SEO Keyword Types (with Examples)

4 Types of Keywords in SEO (+ Examples)

Learn the four types of keywords in SEO and how to optimize your content to rank for each type of keyword.

Top 11 SERP Monitoring Tools 2024

11 Best SERP Monitoring Tools for 2024

Check out our list of the top tools you can use to track your rankings on search engine results pages.

SERP Analysis Tools: A Guide to Usage

SERP Analysis Tools & How to Use Them

Take a dive into the tools you need to analyze SERPs and find SEO opportunities.

View Competitors’ Facebook Ads

How To See Your Competitors’ Facebook Ads

Wondering what your competitors‘ Facebook ads look like? Follow this workflow.

WordPress SEO: The Ultimate Guide

The Ultimate Guide to WordPress SEO

Learn how to optimize your WordPress website for search engines and rank higher in search results.