1

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) {

3 Answers 3

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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        
}

Comments

0

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.

1 Comment

It will never be true, because there is 'numberposts' => 10, so it will return at most 10 attachments.

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.