【问题标题】:Wordpress get image url (currently using wp_get_attachment_url)Wordpress 获取图片 url(目前使用 wp_get_attachment_url)
【发布时间】:2012-04-30 19:37:07
【问题描述】:

在 wordpress 中获取图片附件 url 有点麻烦。到目前为止,这是我的代码:

<?php // find images attached to this post / page.
            global $post;
            $thumb_ID = get_post_thumbnail_id( $post->ID );
            $args = array(
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'numberposts' => -1,
                'orderby' => 'menu_order',
                'order' => 'ASC',
                'exclude' => $thumb_ID,
                'post_parent' => $post->ID
            );
            $images = get_posts($args);
            ?>

            <?php // Loop through the images and show them

            if($images)
            {
            foreach($images as $image)  
            {

            echo  wp_get_attachment_image_url($image->ID, $size='attached-image');

            }
            }

?>

什么都不返回。如果我将wp_get_attachment_image_url($image-&gt;ID, $size='attached-image'); 换成wp_get_attachment_image($image-&gt;ID, $size='attached-image');,这可以正常工作,但会带来图片而不仅仅是网址。

【问题讨论】:

  • 我相信您正在寻找 wp_get_attachment_url( $id ); 或 wp_get_attachment_image_src( $attachment_id, $size, $icon ); - 您引用的函数不是 WP 函数。
  • 对不起,我对 php 还很陌生。我将如何使用上面的代码循环遍历所有图像并输出 url?
  • 在阅读了您的评论和您的问题后,我意识到可能还有其他事情发生:您想要所有附加的图像,还是只想要特色图像?您的代码 get_post_thumbnail_id 仅获取特色图片。您的评论表明您希望查看该帖子的所有图片 - 对吗?
  • 是的,我正在尝试获取附加图像的 URL,不包括特色图像。我在发布后使​​用$attachment_id = $image-&gt;ID; // attachment ID $image_attributes = wp_get_attachment_image_src( $attachment_id, 'full', false ); // returns an array echo '&lt;img src="'; echo $image_attributes[0]; echo '"&gt;'; 成功实现了这一目标

标签: image wordpress url attachment


【解决方案1】:

以下代码将遍历所有图片附件并输出 src url。请注意,根据您的需要,显示了两种方法。

<?php

    global $post;
    $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_mime_type' => 'image', 'post_status' => null, 'post_parent' => $post->ID ); 
    $attachments = get_posts($args);
    if ($attachments) {
            foreach ( $attachments as $attachment ) {
                    // Method #1: Allows you to define the image size
                    $src = wp_get_attachment_image_src( $attachment->ID, "attached-image");
                    if ($src) {echo $src[0];}
                    // Method #2: Would always return the "attached-image" size
                    echo $attachment->guid;
            }
    }

?>

【讨论】:

  • 谢谢!我设法使用 wp_get_attachment_src 实现了类似的目标,但方式略有不同。你的方式更干净,谢谢!
  • 附件的 GUID 属性就是一个 GUID——不应将其视为可在任何地方使用的 URL。最后一行 'echo $attachment->guid' 可以输出实际上不是真实 URL 的 URL。见pods.io/2013/07/17/dont-use-the-guid-field-ever-ever-ever
猜你喜欢
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 2012-06-30
  • 1970-01-01
  • 2018-05-09
  • 2013-12-18
相关资源
最近更新 更多