【问题标题】:PHP/Wordpress: Echo <div> containing all attached images of a post?PHP/Wordpress:Echo <div> 包含帖子的所有附加图像?
【发布时间】:2018-01-14 07:56:51
【问题描述】:

对于 Wordpress 主题,我想创建一个函数(包含在 content.php 中),它获取附加到帖子的所有图像,为每个图像创建一个 &lt;img&gt;-string,最后创建并回显一个 @ 987654322@ 包含所有这些&lt;img&gt;-strings。

到目前为止,我能够获取所有图像并创建&lt;img&gt;-strings,但我很难将它们放入新的&lt;div&gt;。到目前为止,我的功能代码如下所示:

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 ???

    }
}

这成功地为每个图像创建了一个&lt;img&gt;-tag 并对其进行回显,以便图像显示在网站上。但是,我需要在&lt;div&gt; 中回显它们,而不是仅仅回显图像。有没有办法将为每个图像创建的所有字符串放入一个数组中,然后我可以将其放入 &lt;div&gt; 的新字符串中?

【问题讨论】:

  • 每个带有新 div 的图像标签还是一个 div 中的所有图像?
  • @Khushboo 一个 div 中的所有图像

标签: php html css arrays wordpress


【解决方案1】:

试试这个。抱歉,手机发帖。

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>";

    }
}

【讨论】:

  • 感谢您的快速回答,现在无法测试,但稍后会测试。真的那么简单吗?只需将 foreach 循环包装在几个打印
    -tag? 的回声中
  • 是的,有时间可以测试一下?
  • 完美,您的解决方案正是我所需要的,谢谢!
猜你喜欢
相关资源
最近更新 更多
热门标签