I am working on a custom query to show a few posts. I am able to output all the post ID's. I am trying to turn these ID's into an array so I can use 'post__in' => $myarray in my query. How can I do this?

            $allposts = $wpdb->get_results("SELECT `music_id` FROM `custom_table` ORDER BY id DESC LIMIT 5");
              foreach ($allposts as $singlepost) {
                       echo '<p>' .$singlepost->music_id. '</p>';

Use $wpdb->get_col. It will return a one-dimensional array that you can use in post__in

$allposts = $wpdb->get_col("SELECT `music_id` FROM `custom_table` ORDER BY id DESC LIMIT 5");
  • Hey thank you Shane. This works great and is the most simple solution. Exactly what I was looking for. – JediTricks007 Sep 3 '15 at 5:09
$id = array();
 foreach ($allposts as $singlepost) {
      $id[]= $singlepost->music_id;
  • Thank you very much. This seems to be working. I had to add this $recentlistens = array($id[0], $id[1], $id[2], $id[3],$id[4]); Is there a better way to do that? – JediTricks007 Sep 2 '15 at 23: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.