0

I want to check if a variable contains list of post IDs, then I want to query the posts of those IDs only, but if that variable is empty then I want to display all posts.

Problem: If I supply IDs to post__in, then it gets the posts with those IDs, but if it is empty then it should return all posts but it returns no any post.

For example, the following code will get the posts with IDs 1,2,3. However this will return no any post if the $ids is empty. Shouldn't it return ALL posts in that case? How can I get all posts if $ids is empty ie. $ids = ""; ?

$ids = '1,2,3';
$arr = explode("," ,$ids);

$args = array(
    'posts_per_page' => $number,    
    'post__in' => $arr, 
);
  • What do you mean by "if it is empty"? How do you check emptiness? WordPress should ignore post__in param if it's really empty - $q['post__in'] == false. – Krzysiek Dróżdż Nov 13 '13 at 11:19
  • I meant if $ids = ''; – jay Nov 13 '13 at 11:33
0

It looks like WordPress doesn't ignore empty post__in param. So you'll have to do this yourself like this...

$ids = '1,2,3';

if ( $ids ) {
    $arr = explode("," ,$ids);

    $args = array(
        'posts_per_page' => $number,    
        'post__in' => $arr
    );
} else {
    $args = array(
        'posts_per_page' => $number
    );
}
1

An alternative to Krysiek's answer. They both should accomplish the same thing and only add the post__in parameter if the $ids exist.

$ids = '1,2,3';
$arr = explode("," ,$ids);

$args = array(
    'posts_per_page' => $number,    
);

if( $ids )
   $args['post__in'] = $arr; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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