0

In my searchform.php I want to query the values of a custom field, add them into a dropdown, and return a link to a corresponding page upon submit.

Thus far I can create the values dropdown:

global $wpdb;
$values = $wpdb->get_col("SELECT meta_value
    FROM $wpdb->postmeta WHERE meta_key = 'Price'" ); 

However, this just gives me an array of values, is there an object that contains the page information and the custom field values?

0
0

Option 1 - Grab the post ID at the same time

You can also select the post_id field when you running your query, allowing you to then get the post with a call to get_post($values->post_id); (if required).

global $wpdb;
$query = $wpdb->prepare('
    SELECT p.post_id, p.meta_value
    FROM %1$s AS p
    WHERE p.meta_key = "post_views_count"',
    $wpdb->postmeta
);
$results = $wpdb->get_results($query);

You've not stated how your form submittion is being handeled, but you could add the post ID as the value in your dropdown, and then during handeling you have the ID and can do what you desire with it.

if(!empty($results)) :  // Ensure there are results to create a dropdown from

    echo '<select>'."\n";
    
    foreach($results as $result) :  // Loop through each result and output an option
    
        printf(
            "\t".'<option value="%1$s">%2$s</option>'."\n",
            $result->post_id,
            $result->meta_value
        );
        
    endforeach;
    
    echo '</select>'."\n";
    
endif;

Option 2 - Grab the whole post and join it to the meta_value -

If the above doesn't go far enough, you can select both the meta_value and the Post related to it using the query below. From there, you can do whatever you desire as you'd have the full post.

Note however that it's recommended that you only select the fields that you acutally want (it's quicker), so I'd advice replacing p.* with the only what you intend to use.

global $wpdb;
$query = $wpdb->prepare('
    SELECT p.*, pm.meta_value
    FROM %1$s AS p
    JOIN %2$s AS pm ON (p.ID = pm.post_id)
    WHERE pm.meta_key = "post_views_count"',
    $wpdb->posts,
    $wpdb->postmeta
);
$results = $wpdb->get_results($query);
3
  • As for form handling, i am using the built in wp search. My form posts to "/" and is named /s. Is there a way you would recommend?
    – Chris
    Feb 25 '15 at 17:20
  • The option 2 query was close to what I needed, I adjusted some things and got it. $query = $wpdb->prepare(' SELECT p.post_id, p.meta_value, pm.post_title FROM %1$s AS p JOIN %2$s AS pm ON (p.post_id = pm.ID) WHERE p.meta_key = "Price"', $wpdb->postmeta, $wpdb->posts
    – Chris
    Feb 25 '15 at 19:18
  • Glad to have helped :)
    – David Gard
    Feb 26 '15 at 7:15

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.