1

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

7

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 );
}
4
  • Wow ... wp_list_pluck - you learn something new from a 9 year old post every day around here. Thanks! Commented Aug 4, 2023 at 23:22
  • 1
    @squarecandy noways you can use array_column() that is PHP 5.5+ so not an option 9 years ago in WP code. :)
    – gmazzap
    Commented Aug 8, 2023 at 13:10
  • That's great for arrays, but that doesn't support objects too like wp_list_pluck does. Commented Aug 8, 2023 at 17:24
  • @squarecandy array_column supports objects as well since PHP 7.0 which is the min required version for WP these days 3v4l.org/aqmP6
    – gmazzap
    Commented Aug 8, 2023 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.