WordPress provides an advantage of action hook with which we can customize everything without touching core files of WordPress and that is the main reason for the success of WordPress.We can use the hook to extend any architecture of WordPress.
Today I am going to explain how to Customize Search Results in WordPress.As I said, WordPress provide the hook, we will use a hook to customize search result and its pretty easy.
Let’s understand by code:
First of all, Add filter to customize your query of search so I am going to add filter in posts_join
,posts_where
and posts_groupby
.
1 2 3 4 5 6 7 8 | if ( !is_admin() ) { // custom search add_filter( 'posts_where', 'custom_search_where' ); add_filter( 'posts_groupby', 'custom_search_groupby' ); } |
Now, create a function for your require query and apply code as you require.
Let’s understand by code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | // search with join function custom_search_join($join) { if ( is_search() && isset($_GET['s'])) { global $wpdb; $join = " LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id "; } return($join); } // search with groupby function custom_search_groupby($groupby) { if ( is_search() && isset($_GET['s'])) { global $wpdb; $groupby = " $wpdb->posts.ID "; } return($groupby); } // search with where function custom_search_where($where) { global $wpdb; $old_where = $where; if (is_search() && isset($_GET['s'])) { // added custom fields here to include them in search results $customs = array('custom_field1', 'custom_field2'); $query = ''; foreach($customs as $custom) { $query .= " OR ("; $query .= "($wpdb->postmeta.meta_key = '$custom')"; $query .= " AND ($wpdb->postmeta.meta_value LIKE '%<meta_value>%')"; $query .= ")"; } $where .= " <your_where_condition>"; if (!empty($query)) { $where = " {$old_where} AND ({$query}) AND ($wpdb->posts.post_status = 'publish')"; } } return($where); } |
You need to place above code into your theme’s functions.php
file and customize code where you want.You can add your own query.This is very easy, and a somewhat difficult thing to explain.
Also Read:
Customize Upload mime types in WordPress
How to use Ajax in WordPress with example
To Replace Navigation Text to Icon in WordPress
That’ it. Like I said, quick and simple.Check your search result and have a fun with WordPress.
Don’t hesitate to use this code in your WordPress projects and post your comments if you need help. As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.