Custom Field Search not working correctly
-
Hi
I am trying to alter the search function of wordpress without using a plugin.
I need the search to search only the post title and the postmeta table where the meta_key = ‘agent_skype’
The query which I am trying to code into the search function is
SELECT DISTINCT * FROM wp_posts LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'agent_skype' WHERE ( wp_posts.post_title LIKE '%SearchString%' ) OR ( wp_postmeta.meta_value LIKE '%SearchString%' )
I have used the following code to search only the post title
function wpse_11826_search_by_title( $search, $wp_query ) { if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) { global $wpdb; $q = $wp_query->query_vars; $n = ! empty( $q['exact'] ) ? '' : '%'; $search = array(); foreach ( ( array ) $q['search_terms'] as $term ) $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n ); if ( ! is_user_logged_in() ) $search[] = "$wpdb->posts.post_password = ''"; $search = ' AND ' . implode( ' AND ', $search ); } return $search;} add_filter( 'posts_search', 'wpse_11826_search_by_title', 10, 2 );
Which works then I used the below to try and extend the search function to include the custom field
function cf_search_join( $join ) { global $wpdb; if ( is_search() ) { $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id AND '. $wpdb->postmeta . 'meta_key = Agent_Skype'; } return $join; } add_filter('posts_join', 'cf_search_join' ); function cf_search_where( $where ) { global $wpdb; if ( is_search() ) { $where = preg_replace( "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/", "(".$wpdb->posts.".post_title LIKE $1) OR EXISTS (".$wpdb->postmeta.".meta_value LIKE $1)", $where ); } return $where; } add_filter( 'posts_where', 'cf_search_where' ); function cf_search_distinct( $where ) { global $wpdb; if ( is_search() ) { return "DISTINCT"; } return $where; } add_filter( 'posts_distinct', 'cf_search_distinct' );
When using this it does not return the same results as running the query. Can anyone offer any insight in what I’m doing wrong?
I would prefer not to use a plugin for this, as this is also a learning exercise for me.
Thanks
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘Custom Field Search not working correctly’ is closed to new replies.