WordPress条件后循环

问题描述 投票:1回答:3

我有一个非常简单的问题,我想为以下数组添加一个条件if语句。如果至少有10个附件,我只想在小部件中显示附件,否则我不想显示小部件。

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

如何为此阵列抓取的特定数量的附件创建if语句?例如,“if($ attachments> 10){

php wordpress
3个回答
0
投票

您拥有的代码最多只能获得10个帖子,'numberposts' => 10,。要检索作为附件的所有帖子,您可以使用'numberposts' => -1,。参考https://developer.wordpress.org/reference/functions/get_posts/

然后你可以检查是否至少有10个附件:

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

1
投票

你传递给get_posts的args正在呼吁10帖子,所以你永远不会得到更多的答复。

'numberposts' => 10,

但是,如果您希望显示条件恰好为10:

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

0
投票

这是你的追求吗?

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

get_posts()返回一个帖子数组,因此您只需计算它返回的数组中的元素数。

© www.soinside.com 2019 - 2024. All rights reserved.