0

I have a strange situation.

I want to store the IDs from a wp_query in a variable.

So far i have the following:

    $loop = new WP_Query( array(
    'post_type'         => 'programma',
    'post_parent'       =>  0,
    'posts_per_page'    => -1,
    
) );
    if ( $loop->have_posts() ): 
    while ( $loop->have_posts() ) : $loop->the_post();
    $ids[] = get_the_ID();

Now the strange thing is: when i print_r($ids), i get the following:

Array ( [0] => 5404 ) 
Array ( [0] => 5404 [1] => 5307 )
Array ( [0] => 5404 [1] => 5307 [2] => 5308 )

Why is this? And how can i prevent this? I only want the last array to be stored.

4
  • Can you provide the full code ? (with the var_dump) Commented Apr 28, 2021 at 12:10
  • the print_r is inside your loop? Commented Apr 28, 2021 at 12:12
  • @HowardE: yes print_r is in this case inside the loop, but i printed it outside the loop as well, same result. Commented Apr 28, 2021 at 12:13
  • @Bazaim: var_dump results in: array(1) { [0]=> int(5404) } array(2) { [0]=> int(5404) [1]=> int(5307) } array(3) { [0]=> int(5404) [1]=> int(5307) [2]=> int(5308) } Commented Apr 28, 2021 at 12:14

1 Answer 1

1

If the print_ris inside the loop, you see the construction of your array.

You may only want to get list of ids:
https://developer.wordpress.org/reference/classes/wp_query/#return-fields-parameter

$ids = new WP_Query([
    'post_type'         => 'programma',
    'post_parent'       =>  0,
    'posts_per_page'    => -1,
    'fields'            => 'ids'
]);
Sign up to request clarification or add additional context in comments.

1 Comment

You are right, the error was(is) the print inside the loop.... Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.