Brayden
Brayden

Reputation: 125

WordPress Conditional Post Loop

I have a very simple problem, I would like to add a conditional if statement for the following array. I would ONLY like to show the attachments in a widget if there is at least 10 attachments, otherwise I don't want to display the widget.

  $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'numberposts' => 10,
        'post_status' => 'published',
        'post_parent' => null,
        );
    $attachments = get_posts($args);

How would I create an if statement for a specific number of attachments grabbed by this array? For example, "if ($attachments > 10) {

Upvotes: 1

Views: 47

Answers (3)

BugsArePeopleToo
BugsArePeopleToo

Reputation: 2996

The args you pass into get_posts are calling for 10 posts, so you will never get more than that in the response.

'numberposts' => 10,

However, if you want the condition of display to be that it gets exactly 10:

if (count($attachments) === 10) {
  // proceed
}

Upvotes: 1

Charlie Stanard
Charlie Stanard

Reputation: 1058

The code you have will only ever get a maximum of 10 posts, 'numberposts' => 10,. To retrieve all posts that are attachments you can use 'numberposts' => -1,. Reference https://developer.wordpress.org/reference/functions/get_posts/.

Then you can check to see if there are at least 10 attachments:

if (count($attachments) >= 10) { 
    // display widget        
}

Upvotes: 0

Jack Templeman
Jack Templeman

Reputation: 358

Is this what your after?

if (count($attachments) > 10) {
  // code here
}

get_posts() returns an array of posts, so you can just count the number of elements in the array it returns.

Upvotes: 0

Related Questions