I'm looking to pull up an array of posts based on custom field values:

function GetPrimaryLinks($product){
echo '<ul>';
$args = array( 
              'product' => $product, 
              'meta_key' => 'primary_link', 
              'meta_value' => array(
                                    'top_comments') );
$primarylinks = get_posts( $args );
foreach ($primarylinks as $post) :  setup_postdata($post);
echo '<li><a href="'.the_permalink().'">'.the_title().'</a></li>';
echo '</ul>';

Therefore, I can reuse the function on various products to pull up the pages for 'Home', "Obj. Handling", etc. and only use one SQL query each time.

This script obviously doesn't work because it's looking for posts with an array of meta_values, but I'm wondering if there's a way to write the function in one SQL query, rather than breaking up the meta_values into individual queries.

  • Are you trying obtain all posts with all those meta values, or posts with at least one of them...? – Stephen Harris Feb 20 '12 at 16:31
  • @StephenHarris To clarify, one post would have primary_link=>'home', another would have primary_link=>'obj_handling', etc. The function would output a list of primary links based on those meta values. So, more of the latter but the post would have only one value. – AlxVallejo Feb 20 '12 at 16:36

Look at the meta_query argument, and the "IN" option for the "Compare" operator.

Your query would look something like:

$args = array( 
      'product' => $product, 
      'meta_query' => array(
              'key' => 'primary_link', 
              'value' => array(
              'compare' => 'IN' )
| improve this answer | |
  • 1
    Doh, you beat me to it! It should be an array of arrays though. :) – Cristian Feb 20 '12 at 16:32
  • Ah, yup! will fix ;) – goldenapples Feb 20 '12 at 16:33
  • For some reason, I thought I read that I should use WP_Query instead of get_posts? – AlxVallejo Feb 20 '12 at 17:00
  • @AlxVallejo No. Only for the 2nd query. – kaiser Feb 20 '12 at 17:51
  • 1
    @AlxVallejo get_posts works just as well as WP_Query for something like this. WP_Query also calls setup_postdata, so that you can use template tags like <?php the_title(); ?> and so on. But if you call setup_postdata yourself, as you're doing, they're basically identical functions. – goldenapples Feb 20 '12 at 18:12

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.