How can I get an array of all IDs from the current queried object?

I am trying to join an array of post IDs together. Right now, it seems my code is creating a separate array for each ID, instead of one array with each ID.

This is the code that I have come up with. It is inside of an include inside a taxonomy.php file.

So basically, I am trying to get the ID of each post that would result from the query of the given taxonomy term.

I feel like I am missing something very obvious? I have tried taking the variable outside of the loop but it will only output the first post ID.

<?php 

        if( function_exists( 'wpseo_local_show_map' ) ) {

        while (have_posts()) : the_post();

            $post_ids = get_the_ID();

            var_dump($post_ids);

        endwhile;

                    $params = array(
                    'id' => $post_ids,
                    'echo' => true,
                    'width' => 425,
                    'height' => 350,
                    'zoom' => 10,
                    'show_route' => true
                    );
                     wpseo_local_show_map( $params );
                }

?>

The var_dump looks like this. Can anyone point me in the right direction?

1 Answer
1

You are overwriting $post_ids variable on every while loop, never collecting them.

That can be solved using

$post_ids = array();

while (have_posts()) : the_post();

  $post_ids[] = get_the_ID();

endwhile;

var_dump($post_ids); // this is an array of ids

However there is simpler way, you can skip the whle cycle and simply run:

if( function_exists( 'wpseo_local_show_map' ) && have_posts() ) {

  // this is an array of ids
  $post_ids = wp_list_pluck( $GLOBALS['wp_query']->posts, 'ID' ); 

  $params = array(
    'id' => $post_ids,
    'echo' => true,
    'width' => 425,
    'height' => 350,
    'zoom' => 10,
    'show_route' => true
  );
  wpseo_local_show_map( $params );
}

Leave a Comment