21

I've got a string with post ID's: 43,23,65.
I was hoping I could use get_posts() and use the string with ID's as an argument.

But I can't find any functions for retrieving multiple posts by ID.

Do I really have to do a WP_query?

I've also seen someone mention using tag_in - but I can't find any documentation on this.

36

You can use get_posts() as it takes the same arguments as WP_Query.

To pass it the IDs, use 'post__in' => array(43,23,65) (only takes arrays).

Something like:

$args = array(
    'post__in' => array(43,23,65)
);

$posts = get_posts($args);

foreach ($posts as $p) :
    //post!
endforeach;

I'd also set the post_type and posts_per_page just for good measure.

  • This doesn't work. – Dissident Rage Aug 5 '15 at 19:22
  • No? Are you passing it as an array? Using two underscores (post__in vs post_in)? Passing a post_type? – CookiesForDevo Aug 6 '15 at 1:10
  • 1
    If you're getting a custom post type, use the post_type argument, and if you want more than 5 results, add the 'nopaging' => true option. If you have a comma seperated string instead of an array, use explode(',',$input); to convert to array. – ejazz Jan 19 '17 at 13:48
  • 1
    If you wanted to keep the order of the posts the way they're passed by the array, make sure to add 'order_by' => 'post__in' to your $args. – rob_st Oct 12 '17 at 10:17
  • beware using post_type parameter. In case of post, function will return ALL content types, including your custom ones, not just post. – Fusion Apr 23 at 11:49
3

If you can't get the above to work, make sure you add post_type:

$args = array(
    'post_type' => 'pt_case_study',
    'post__in' => array(2417, 2112, 784)
);

$posts = get_posts($args);

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.