How to make WP_Query ‘post__in’ accept an array?

I have a function that returns a comma separated list of post ids that a particular user can access. I want to use this list in a WP_Query loop.

The custom function:

Read More
$array = user_albums();
foreach( $array as $post ) {
    if( !in_array( $post->ID, $array ) )
        $ids[] = $post->ID;
}
$access_ids = implode( ', ', $ids );

So here is the situation:

  1. On my test site the id list is 158, 162, 145, 269.
  2. Inserting the list of ids returns only the first post. 'post__in'=> array(
    $access_ids ),
  3. Inserting the list of ids not in an array returns an error. 'post__in'=> $access_ids ,
  4. Inserting the post ids manually returns correct
    posts 'post__in'=> array( 158, 162, 145, 269 ),

What could I be doing wrong?
I appreciate any help.

Related posts

Leave a Reply

3 comments

  1. $access_ids is a string. post__in accepts an array.

    So instead of $access_ids you could use 'post__in'=> $ids skipping the $access_ids = implode( ', ', $ids ); all together.

  2. That implode() is probably what breaks things:

    $access_ids = '158, 162, 145, 269';
    
    $array = array($access_ids); //wrong
    var_dump( $array ); 
    // array
    //  0 => string '158, 162, 145, 269' (length=18)
    
    $array = array_map( 'trim', explode( ',', $access_ids ) ); // right
    var_dump( $array ); 
    //array
    //  0 => string '158' (length=3)
    //  1 => string '162' (length=3)
    //  2 => string '145' (length=3)
    //  3 => string '269' (length=3)