PHP / Wordpress:Echo <div>包含帖子的所有附加图像?

时间:2018-01-13 14:39:19

标签: php html css arrays wordpress

对于Wordpress主题,我想创建一个函数(包含在content.php中),它将所有图像附加到帖子上,为每个图像创建一个<img> - 字符串,最后创建和回声<div>包含所有这些<img> - 字符串。

到目前为止,我能够获取所有图像并创建<img> - 字符串,但我很难将它们放入新的<div>中。我到目前为止运行的代码看起来像这样:

function create_imageslideshow() {

    // Get the post ID
    $iPostID = $post->ID;

    // Get images for this post
    $arrImages = get_attached_media( 'image' . $iPostID  );

    // If images exist for this post
    if($arrImages) {

        // Get array keys representing attached image numbers
        $arrKeys = array_keys($arrImages);

        foreach ($arrKeys as $iNum) {

          // Get the full sized image url for the attachment
          $sImageUrl = wp_get_attachment_url($iNum);

          // Build the <img> string (parse regular <img>-tag)
          $sImgString = 

            '<img id="' . $iNum . '"" src="' . $sImageUrl . '"  alt="Thumbnail Image" title="Thumbnail Image" />';

          // Print the image
          echo $sImgString;
        }

        // Build slideshow ???

    }
}

这为每张图片成功创建了一个<img>标签并回显它,以便图片显示在网站上。但我不是只回显图像,而是需要它们在<div>内回显。有没有办法将为每个图像创建的所有字符串放入一个数组中,然后我可以将其放入<div>的新字符串中?

1 个答案:

答案 0 :(得分:0)

试试这个。对不起,通过电话发帖。

function create_imageslideshow() {

// Get the post ID
$iPostID = $post->ID;

// Get images for this post
$arrImages = get_attached_media( 'image' . $iPostID  );

// If images exist for this post
if($arrImages) {

    echo "<div class='test'>";

    // Get array keys representing attached image numbers
    $arrKeys = array_keys($arrImages);

    foreach ($arrKeys as $iNum) {

      // Get the full sized image url for the attachment
      $sImageUrl = wp_get_attachment_url($iNum);

      // Build the <img> string (parse regular <img>-tag)
      $sImgString = 

        '<img id="' . $iNum . '"" src="' . $sImageUrl . '"  alt="Thumbnail Image" title="Thumbnail Image" />';

      // Print the image
      echo $sImgString;
    }

    echo "</div>";

    }
}