查找图像URL的附件页面URL

时间:2019-04-27 22:27:08

标签: php wordpress

我正在使用以下代码将所有图片网址附加到帖子上。

global $post;

 $thumbnail_ID = get_post_thumbnail_id();

 $images = get_children( array('post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );

 if ($images) :

     foreach ($images as $attachment_id => $image) :

         $img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); //alt
         if ($img_alt == '') : $img_alt = $image->post_title; endif;

         $big_array = image_downsize( $image->ID, 'large' );
         $img_url = $big_array[0];
 endforeach; endif; }

我得到的输出是这样的:

https://www.example.com/wp-content/uploads/2019/01/image.gif

我需要找到的是此图像的附件页面URL,它类似于https://www.example.com/post-name/image-22

我尝试使用wp_get_attachment_image,但是输出不是我所需要的。

我知道该怎么做吗?

1 个答案:

答案 0 :(得分:0)

您正在寻找get_attachment_link返回漂亮链接,需要确保将永久链接结构设置为漂亮链接。

https://codex.wordpress.org/Function_Reference/get_attachment_link

页面示例:

<?php 
$attachment_id = 1; // ID of attachment
$attachment_page = get_attachment_link( $attachment_id ); 
?>
<a href="<?php echo $attachment_page; ?>"><?php echo get_the_title( $attachment_id ); ?></a>