If you’ve ever had to search custom post types, this function will come in handy:
<?php
function search_by_post_and_meta_fields($args) {
global $wpdb;
$defaults = array(
'post_type' => 'post',
'post_fields_to_search' => false,
'meta_fields_to search' => false,
'search_term' => false
);
extract(wp_parse_args($args, $defaults));
if(($post_fields_to_search or $meta_fields_to_search) and $search_term) {
$ids = array();
$query = "SELECT DISTINCT $wpdb->posts.ID
FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
WHERE ($wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = '$post_type') AND (";
$where_parts = array();
if(is_array($post_fields_to_search)) {
foreach($post_fields_to_search as $field) {
$where_parts[] = "$wpdb->posts.$field LIKE '%$search_term%'";
}
}
if(is_array($meta_fields_to_search)) {
foreach($meta_fields_to_search as $field) {
$where_parts[] = "( $wpdb->postmeta.meta_key = '$field' AND $wpdb->postmeta.meta_value LIKE '%$search_term%' )";
}
}
if(count($where_parts)) $query .= implode(' OR ', $where_parts);
$query .= ") ORDER BY $wpdb->posts.ID ASC";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result){
$ids[] = $result['ID'];
}
return $ids;
}
return false;
}
?>
Then in your template, you just call it like follows:
<?php
$args = array(
'post_type' => 'listing',
'post_fields_to_search' => array('post_title', 'post_content'),
'meta_fields_to_search' => array('_tags'),
'search_term' => 'hello'
);
$post_ids = search_by_post_and_meta_fields($args);
foreach($post_ids as $post_id) {
$post = get_post($post_id);
setup_postdata($post);
}
?>



