0

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( 'home', 'obj_handling', 'standalone_doc', 'advantages', 'weaknesses', 'top_comments') ); $primarylinks = get_posts( $args ); foreach ($primarylinks as $post) : setup_postdata($post); echo '<li><a href="'.the_permalink().'">'.the_title().'</a></li>'; endforeach; 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.

2
  • Are you trying obtain all posts with all those meta values, or posts with at least one of them...? Commented Feb 20, 2012 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. Commented Feb 20, 2012 at 16:36

1 Answer 1

1

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( array( 'key' => 'primary_link', 'value' => array( 'home', 'obj_handling', 'standalone_doc', 'advantages', 'weaknesses', 'top_comments' ), 'compare' => 'IN' ) ) ); 
7
  • 1
    Doh, you beat me to it! It should be an array of arrays though. :) Commented Feb 20, 2012 at 16:32
  • Ah, yup! will fix ;) Commented Feb 20, 2012 at 16:33
  • For some reason, I thought I read that I should use WP_Query instead of get_posts? Commented Feb 20, 2012 at 17:00
  • @AlxVallejo No. Only for the 2nd query. Commented Feb 20, 2012 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. Commented Feb 20, 2012 at 18:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.