【问题标题】:Get WordPress images using media ID in a foreach loop在 foreach 循环中使用媒体 ID 获取 WordPress 图像
【发布时间】:2015-06-11 07:41:00
【问题描述】:

我已经看到如何获取媒体库中的所有图像,反之亦然,从帖子库中获取图像,精选缩略图但尚未找到基于图像 ID 的方法。

我正在创建一个自定义画廊简码,并有一个名为 ids 的属性,就像默认内置的 wordpress 画廊一样,它将基于 id 输出图像。

我也查看了 WordPress 文档,要获取图片网址,我们需要 wp_attachment_src 函数。

我有简码:

// 他们输入的 id 是图片 id,不是发布图片或精选缩略图,它来自媒体库的特定图片 id

[some-gallery ids="8,4,23,9"]

add_shortcode('some-gallery', 'example_shortcode');
function example_shortcode($atts){
   extract(shortcode_atts(array(
      'ids' => '8,6,9', // 8 is just a default placement
   ), $atts));


$arr = explode(",",$ids); //convert list of ids as an array
echo "<div id=\"container\">\n";
foreach($arr as $id) {
$img = wp_get_attachment_image_src($id); //get images using image id not working!!
    echo "<div>$img</div>\n"; //result is the word Array
} 
echo "</div>\n";
}

【问题讨论】:

    标签: php jquery wordpress image


    【解决方案1】:

    你试过 wp_get_attachment_image 吗?

    <?php wp_get_attachment_image( $attachment_id, $size, $icon, $attr ); ?>
    

    wp doc

    【讨论】:

    • 你能用循环给出完整的答案吗?
    【解决方案2】:

    使用wp_get_attachment_image_src获取图片的url。

    <?php wp_get_attachment_image_src( $attachment_id, $size, $icon ); ?>
    

    它返回一个有序数组,其值对应于图像附件(或代表任何附件的图标)的 (0) url、(1) 宽度、(2) 高度和 (3) 比例。

    这是一个例子

    $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'product_image_size');
    

    【讨论】:

    【解决方案3】:

    我发现如果我按属性分解图像结果是否有效。

    $arr= explode(",",$ids); //prints an array of numbers
    
    echo "<div id=\"container\">\n";
    foreach($arr as $id) {
      $img = wp_get_attachment_image_src($id, medium);
      echo "<div class=\"$class\"><img src=\"$img[0]\" width=\"$img[1]\" height=\"$img[2]\"></div>\n";
    }
      echo "</div>\n";
    

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2014-01-06
      • 2021-01-29
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多