Custom Fields Search
-
Is it possible to write a search that asks for various different Meta_Keys?
I have posts with multiple custom field entries.
Lets say a user wants to search for posts where I was reading a specific book (entered in the custom field) and only display the ones where I was happy when posting (another custom field).
More Background:
I figured out how to modify the search form. I entered all the inputs just to test. Then when you set the form action to home and request the variables you just set, you can call them (did a few echos to test. said “you serached for $var1 $var2, etc)
Got it hooked up, but it doesn’t work when I go trying to define the same thing over and over.
Any suggestions on an approach here?
<?PHP $candy = $_REQUEST['candy'] ; $mood = $_REQUEST['mood'] ; $booktype = $_REQUEST['booktype'] ; $bookpgs = $_REQUEST['bookpgs'] ; ?> <?php $querystr = " SELECT wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = 'candy' AND wpostmeta.meta_value = '$candy' AND wpostmeta.meta_key = 'mood' AND wpostmeta.meta_value = '$mood' AND wpostmeta.meta_key = 'booktype' AND wpostmeta.meta_value = '$booktype' AND wpostmeta.meta_key = 'bookpgs' AND wpostmeta.meta_value = '$bookpgs' AND wposts.post_status = 'publish' AND wposts.post_type = 'post' ORDER BY wposts.post_date DESC "; $pageposts = $wpdb->get_results($querystr, OBJECT); ?>Thanks 🙂
-
@ thebraindonor
Thanks for the link, but this does not really solve the issue of having a search engine that uses certain meta field values to narrow down the search following user-selected combo boxes and check boxes. Or at least I am unable to see how it could.
The code I provided can be used as a starting point to provide the functionality you are looking for. The goal of the search updates I made were look for matches that found in a meta field or the post content.
In order to use the meta fields to narrow down the search, you would need to update the plugin code I provided to include an additional AND clause before the full query is assembled and returned:
$term = $wpdb->escape($var_q); if (!$_GET['sentense'] && Count($search_terms) > 1 && $search_terms[0] != $var_q) { $query .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')"; $query .= " OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}')"; } //begin new code if ($_GET['limit_author']) { $limit_author = $_GET['limit_author']; $query .= " AND ("; $query .= "($wpdb->postmeta.meta_key = 'author')"; $query .= " AND ($wpdb->postmeta.meta_value LIKE '{$n}{$limit_author}{$n}')"; $query .= ") "; } //end new code if (!empty($query)) { $where = " AND ({$query}) AND ($wpdb->posts.post_status = 'publish') "; }I’ve not tested it, but it should give you an idea of how and where to update the query.
The topic ‘Custom Fields Search’ is closed to new replies.