0

我正在尝试在 Wordpress 中获取不同图像大小的列表。我认为这更像是一个 php 问题,所以我在这里而不是在 wordpress 论坛上问它。

这是我的代码:

function ajax_get_latest_posts(){   
   $attachments = get_children(array('post_parent' => $post->ID,
                    'post_status' => 'inherit',
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image',
                    'order' => 'ASC',
                    'orderby' => 'menu_order ID'));

   foreach($attachments as $att_id => $attachment) {
      $large_bg_url = wp_get_attachment_image_src($attachment->ID, 'background-large');
      $medium_bg_url = wp_get_attachment_image_src($attachment->ID, 'background-medium');
      $small_bg_url = wp_get_attachment_image_src($attachment->ID, 'background-small');
      $imagesizes .= array('background_large' => $large_bg_url[0], 'background_medium' => $medium_bg_url[0], 'background_small' => $small_bg_url[0]);
   }

   $allimagesizes = array($imagesizes);

   return $allimagesizes;
}

上面的代码不起作用,但希望能显示我想要实现的目标。问题是 $imagesizes 的连接不正确。下面是我实际需要实现的输出,但我似乎无法弄清楚如何从 foreach 循环中获取此输出。

$allimagesizes = array(
   array(
      'background_large' => 'http://mydomain.com.au/wp-content/uploads/facade.jpg', 
      'background_medium' => 'http://mydomain.com.au/wp-content/uploads/facade-1366x807.jpg', 
      'background_small' => 'http://mydomain.com.au/wp-content/uploads/facade-1024x605.jpg '
   ),
   array(
      'background_large' => 'http://mydomain.com.au/wp-content/uploads/facade-trees.jpg', 
      'background_medium' => 'http://mydomain.com.au/wp-content/uploads/facade-trees-1366x818.jpg', 
      'background_small' => 'http://mydomain.com.au/wp-content/uploads/facade-trees-1024x613.jpg '
   )    
 );
4

2 回答 2

0

你几乎拥有它。

function ajax_get_latest_posts(){   
   $attachments = get_children(array('post_parent' => $post->ID,
                    'post_status' => 'inherit',
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image',
                    'order' => 'ASC',
                    'orderby' => 'menu_order ID'));

   $allimagesizes = array();
   foreach($attachments as $att_id => $attachment) {
      $large_bg_url = wp_get_attachment_image_src($attachment->ID, 'background-large');
      $medium_bg_url = wp_get_attachment_image_src($attachment->ID, 'background-medium');
      $small_bg_url = wp_get_attachment_image_src($attachment->ID, 'background-small');
      $imagesizes = array('background_large' => $large_bg_url[0], 'background_medium' => $medium_bg_url[0], 'background_small' => $small_bg_url[0]);
      $allimagesizes[] = $imagesizes;
   }
   return $allimagesizes;
}

应该管用。

首先,我们在 foreach 之前定义了数组。

从 imagesizes 分配中删除连接运算符。

接下来,我们将在循环中创建的数组推送到循环内的 $allimagessizes 数组中。

于 2013-07-19T05:47:16.663 回答
0

用这个:

$allimagesizes[] = $imagesizes;

放在[]数组名称之后意味着在数组末尾添加一个新元素。

此外,在分配给 时$imagesizes,您应该使用=,而不是.=。后者用于附加到字符串。

于 2013-07-19T05:39:04.750 回答