0

I know there are a lot of good plugins which extend the wordpress search but I want to do the opposite. I want the search only to return posts which have a certain value in a certain post meta field.
How do I do that?

2

I'm not quite sure this is what you want (because it is so ... easy), but all you need to do is add the following inputs to your search form:

<input type="hidden" id="meta_key" name="meta_key" value="YOUR-META-KEY">
<input type="hidden" id="meta_value" name="meta_value" value="YOUR-META-VALUE">

Or, if you want to trigger the search by hand, do it like so:

$search = new WP_Query(array(
    's' => 'YOUR-KEYWORD(S)',
    'meta_key' => 'YOUR-META-KEY',
    'meta_value' => 'YOUR-META-VALUE'
));

// EDIT
If you're dealing with a more complex setup, you might want to use a meta_query:

$search = new WP_Query(array(
    's' => 'YOUR-KEYWORD(S)',
    'meta_query' => array(
        'key' => 'YOUR-META-KEY',
        'value' => 'YOUR-META-VALUE'
    )
));

Or even

$search = new WP_Query(array(
    's' => 'YOUR-KEYWORD(S)',
    'meta_query' => array(
        array(
            'key' => 'YOUR-FIRST-META-KEY',
            'value' => 'YOUR-FIRST-META-VALUE'
        ),
        array(
            'key' => 'YOUR-SECOND-META-KEY',
            'value' => 'YOUR-SECOND-META-VALUE'
        )
    )
));
  • It seems easy but I can't leave out the s parameter. I really only want results with the right meta_value for a specific meta_key but when I leave out the s param I get no results. If I keep it but make it blank -> no results. If I assign the same value I assign to my meta value I get results but from my meta_value and results in the post text. It's nice that I can add the meta query but wordpress will still look for matches in the post text because of 's' – Stephan S. Aug 15 '13 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.