I have a custom post type bananas with a custom field _bananas_size (size is a number). Now I'd like a search field that only searches the custom field size. For example: the visitors selects value 6 and hits search. Then I want only the bananas with a size of 6 or bigger to show up as results. I've found multiple topics on how to handle a search with custom post types. However I haven't found how to limit the search to a custom post field.
What I currently have is this:
<form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform"> <input type="hidden" name="post_type" value="bananas" /> <select name="size"> <option value="4">4</option> <option value="6">6</option> <option value="8">8</option> <option value="10">10</option> </select> <input type="submit" alt="Search" value="Search" /> </form>
$type = 'bananas'; $args=array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'meta_value', 'order' => 'ASC', 'meta_key' => '_bananas_size', 'meta_query' => array( array( 'key' => '_bananas_size', 'value' => $_GET['size'], 'compare' => '>=', 'type' => 'NUMERIC' ) ) ); $my_query = null; $my_query = new WP_Query($args);
This returns a list of all bananas, no matter the size. How can I limit the search to the _bananas_size field?
I tried to do a var_dump like Tomás Cot suggested below but I got no output at all (even not from an
echo "<h1>Size: </h1>";). I changed the searchform.php to:
<form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform"> <input type="search" name="s" placeholder="Search…"> <input type="hidden" name="post_type" value="bananas"> <input type="submit" alt="Search" value="Search" /> </form>
This resulted in the following output:
It turned out that I had a typo in my code (fieldname was _bananassize, not _bananas_size). A very big thanks to @Tomás Cot for finding this! The code he posted below in the answer works great after I fixed my mistake.