Jay-oh
Jay-oh

Reputation: 456

Get all post_id's from current loop in array

So, I'm trying to get all the post_id's from my current loop and store them in an array. I've been reading forums from an hour and non are doing what I'm trying. I've come a long way. And I think I'm almost there. But I could need soms help with the last step.

What I've got so far:

I start my loop with a new WP_Query and add $post_ids = array(); and after the while I add $post_ids[] = get_the_ID();

    <?php $the_query = new WP_Query($args); if ( $the_query->have_posts() ) { 
                $post_ids = array();
                while ( $the_query->have_posts() ) {
                $post_ids[] = get_the_ID();
    ?>

        // Do stuff

    <?php }} else { ?>
      <h3>Noting found, try again</h3>
    <?php } ?>

After the whole loop I do the following:

<pre><?php var_dump($post_ids); ?></pre>

This gives me the following:

array(19) {
  [0]=>
  int(1938)
  [1]=>
  int(1642)
  [2]=>
  int(1217)
  [3]=>
  int(1182)
  [4]=>
  int(1588)
  [5]=>
  int(1180)
  [6]=>
  int(1088)
  [7]=>
  int(1290)
  [8]=>
  int(1938)
  [9]=>
  int(1894)
  [10]=>
  int(1586)
  [11]=>
  int(1176)
  [12]=>
  int(1174)
  [13]=>
  int(1219)
  [14]=>
  int(1756)
  [15]=>
  int(1922)
  [16]=>
  int(1200)
  [17]=>
  int(1803)
  [18]=>
  int(1553)
}

These are all the post_id's I need. But I would like them to have them like: 1938,1643, etc.. so I can use them in an WP_Query again. Do's anyone have an idea how to continue?

Upvotes: 2

Views: 1041

Answers (1)

Angel Deykov
Angel Deykov

Reputation: 1227

You should simply sort your array:

sort($post_ids);// for example
var_dump($post_ids);

Check also this links for more sorting options - ASC, DESC etc. etc.

Upvotes: 1

Related Questions