Wordpress附件网址作为变量

时间:2014-10-21 19:23:17

标签: wordpress attachment

我的帖子附有3张图片,我想将3张图片网址转换为3个单独的变量,并在css中使用背景图片。到目前为止,我已经能够显示3个网址,但无法将它们变成变量,因此我可以将它们称为背景图像。

if ($attachments = get_children(array(
              'post_type' => 'attachment',
              'post_mime_type' => 'image',
              'numberposts' => -1,
              'post_status' => null,
              'post_parent' => $post->ID
                  )));

          foreach ($attachments as $attachment) {

              $mynewarray = wp_get_attachment_image_src($attachment->ID, 'rig');
              $anotherarray = $mynewarray[0];
              echo $anotherarray ;
          }

上面的结果是here

如何将它们分开并将它们转换为变量,例如$backgroundimage1, $backgroundimage2 & $backgroundimage3。所以我可以稍后在页面中调用它们,如下所示

<div class="backgound-image" style="background-image: url(<?php echo $backgroundimage1 ?>)">

1 个答案:

答案 0 :(得分:2)

您可以将所有附件添加到新阵列。并从数组中获取所需的索引。

if ($attachments = get_children(array(
              'post_type' => 'attachment',
              'post_mime_type' => 'image',
              'numberposts' => -1,
              'post_status' => null,
              'post_parent' => $post->ID
                  )));

          $mynewarray = array();
          foreach ($attachments as $attachment) {

              $mynewarray = wp_get_attachment_image_src($attachment->ID, 'rig');
              $anotherarray[] = $mynewarray[0];
              // echo $anotherarray ;
              // not echo, only define in here
          }

在定义之后,你可以得到这些。

echo $mynewarray[0]; // or [1] or [2]