This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Working with WordPress hooks can be a bit tricky, but it’s also super powerful! Today, we’re diving into the posts_search filter. This filter lets you modify the search SQL used in the WHERE clause of WP_Query. To start using it, you’ll need to register it using add_filter. This can be done in your theme’s functions.php file or a custom WordPress plugin. Pro tip: creating a custom plugin for your hooks can prevent any issues when you update your theme.
Here’s how you can use this filter effectively:
Example 1: Search by Title Only
Here’s an example where we customize the search to focus on titles only. This can be useful if you’re trying to refine search results to be more specific to post titles.
function weplugins_search_by_title_only( $search, $wp_query ) { global $wpdb; if(empty($search)) { return $search; // skip processing - no search term in query } $q = $wp_query->query_vars; $n = !empty($q['exact']) ? '' : '%'; // Custom SQL logic here $search = ""; // replace with your SQL logic return $search; } add_filter( "posts_search", "weplugins_search_by_title_only", 10, 2 );
Example 2: Modify Search Defaults
This example demonstrates how you can use the hook to modify the default search behavior according to your website’s requirements. You can conditionally update the $search variable as needed.
function weplugins_modify_posts_search_defaults($search, $query) { // Update the $search variable as per your needs return $search; } add_filter( "posts_search", "weplugins_modify_posts_search_defaults", 10, 2 );
Example 3: Removing a Hook Callback
Sometimes, you might need to remove a previously registered hook. Here’s how you can remove the posts_search filter using remove_filter. Make sure to use the same callback name, priority, and number of arguments.
remove_filter( "posts_search", "weplugins_modify_posts_search_defaults", 10, 2 );
Explore the latest in WordPress
Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.