1

Whilst looking through the codex for the get_posts function, I noticed that in the majority of the examples they do not show an if statement after call to get_posts

Example:

<?php
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ( $postslist as $post ) :
  setup_postdata( $post ); ?> 
    <div>
        <?php the_date(); ?>
        <br />
        <?php the_title(); ?>   
        <?php the_excerpt(); ?>
    </div>
<?php
endforeach; 
wp_reset_postdata();
?>

And:

<?php
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); 
$attachments = get_posts( $args );

**if ( $attachments ) {**
    foreach ( $attachments as $attachment ) {
    echo apply_filters( 'the_title' , $attachment->post_title );
    the_attachment_link( $attachment->ID , false );
    }
}
?>

I'm not sure if the codex is assuming that you will always have posts so no need to check?

I personally always use it, but wonder if someone could enlighten me on if its necessary. When is a right time to use the if statement?

1
  • It's not necessary to me as I tested without if and I could not get any warnings/php errors. – Ahmed Fouad Sep 21 '16 at 12:33
3

In my opinion we cannot guarantee the post existence in db for a specific query. maybe it returns an empty array. so its best practice to use the conditional statement. plus i think we are dealing with an array so to check the empty array we should use php empty function.

for example:

if ( !empty( $attachments ) ) {
  foreach ( $attachments as $attachment ) {
   // do some stuff here.
  }
}
else {
  _e('Sorry! No posts found.');
}
1

The get_posts() can return an empty array

In that case the foreach loop is like:

foreach ( [] as $post ) 
{
    // ...
}

where there's nothing to loop over. This code is valid.

If the code snippet is like:

echo '<ul>';
foreach ( $postslist as $post ) 
{
    // <li>...</li>
}
echo '</ul>';

then we need to check if $postslist is non-empty:

if( $postslist )
{   
    echo '<ul>';
    foreach ( $postslist as $post ) 
    {
        // <li>...</li>
    }
    echo '</ul>';
}

to avoid displaying an empty <ul></ul> list.

This is an example, out of many, where it would make sense to check if the post list is non-empty, but it's not required, like if you only need the count:

echo count( (array) $postslist );

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.