How to Include custom post meta in WordPress search
OR
How to extend search in WORDPRESS
we have three ways to perform this task :-
Solution 1 (This Worked For Me)
function custom_search_where($pieces) {
// filter to select search query
if (is_search() && !is_admin()) {
global $wpdb;
$custom_fields = array('price','manufacturer');
$keywords = explode(' ', get_query_var('s'));
$query = "";
foreach ($custom_fields as $field) {
foreach ($keywords as $word) {
$query .= "((mypm1.meta_key = '".$field."')";
$query .= " AND (mypm1.meta_value LIKE '%{$word}%')) OR ";
}
}
if (!empty($query)) {
// add to where clause
$pieces['where'] = str_replace("((({$wpdb->posts}.post_title LIKE '%", "( {$query} (({$wpdb->posts}.post_title LIKE '%", $pieces['where']);
$pieces['join'] = $pieces['join'] . " INNER JOIN {$wpdb->postmeta} AS mypm1 ON ({$wpdb->posts}.ID = mypm1.post_id)";
$pieces[‘groupby’] = "{$wpdb->posts}.I";
}
}
return ($pieces);
}
add_filter('posts_clauses', 'custom_search_where', 20, 1);
Solution 2
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$meta_args = array(
'relation' => 'OR',
array(
'key' => 'manufacturer',
'value' => $s,
'compare' => 'LIKE',
),
array(
'key' => 'price',
'value' => $s,
'compare' => 'LIKE',
),
);
$query->set('post_type', 'product');
$query->set('meta_query', $meta_args);
}
}
}
add_action('pre_get_posts','search_filter');
Solution 3
function my_smart_search( $search, &$wp_query ) {
global $wpdb;
if ( empty( $search ))
return $search;
$terms = $wp_query->query_vars[ 's' ];
$exploded = explode( ' ', $terms );
if( $exploded === FALSE || count( $exploded ) == 0 )
$exploded = array( 0 => $terms );
$search = '';
foreach( $exploded as $tag ) {
$search .= " AND (
(wp_posts.post_title LIKE '%$tag%')
OR (wp_posts.post_content LIKE '%$tag%')
OR EXISTS
(
SELECT * FROM wp_comments
WHERE comment_post_ID = wp_posts.ID
AND comment_content LIKE '%$tag%'
)
OR EXISTS
(
SELECT * FROM wp_terms
INNER JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id
INNER JOIN wp_term_relationships
ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
WHERE taxonomy = 'post_tag'
AND object_id = wp_posts.ID
AND wp_terms.name LIKE '%$tag%'
)
)";
}
return $search;
}
add_filter( 'posts_search', 'my_smart_search', 500, 2 );
and if your search results comes multiple times then you must read this How to get distinct search results in WORDPRESS
Thanks for give us valuable information If you are Looking for WordPress Support , visit on
ReplyDeleteContact WordPress
WordPress Help
WordPress Contact
How to Include custom post meta in WordPress search Is Very Helpful. Thanks for such Information
ReplyDeleteLooking for WordPress Support Visit :
WordPress Support
WordPress Technical Support
WordPress Support Phone Number
Superb Information
ReplyDeleteWP Support
Awesome Information
ReplyDelete24/7 WordPress Support
24/7 WP Support