如何获取在 Wordpress post 中上传的文件的附件 ID?

How to get Attachment Id of a file uploaded in Wordpress post?

我有 post 并且我在每个 post 中上传了一个文件,如 PDF 或 MS Word 文件(非功能图像)。我想让上传的文件可下载 link。但我无法获取附件 ID。这是我的代码

<?php 
$reports = array(   
 'post_type' => 'post' , 
 'posts_per_page' => 3,
 'category_name' => 'reports'); 
    
 $q_reports = new WP_Query($reports);   
                
 if($q_reports->have_posts()){
 while($q_reports->have_posts()){ 
 $q_reports->the_post();?> 

<a href="<?php echo wp_get_attachment_url($attach_id); ?>" ><?php echo the_title(); ?></a>

不知道怎么才能得到$attach_id.

您可以使用 get_attached_media 获取特定 post 的所有附件。它以附件类型作为第一个参数,请注意,您可以对任何类型的所有图像使用 "images",对任何视频使用 "video",对任何音频文件使用 "audio"。但是要获取文档,您需要指定 mime 类型。仅供参考您可以使用 print_r(get_post_mime_type());

查看所有允许的 mime 类型

因此您可以使用它来获取特定类型的所有附件,如下所示:

  • 图片(任何类型):$attachments = get_attached_media("images", $post->ID );
  • PDF: $attachments = get_attached_media("", $post->ID );
  • Word DOCX 文件$attachments = get_attached_media("application/vnd.openxmlformats-officedocument.wordprocessingml.document", $post->ID );

如果您需要检查多种 MIME 类型(例如 PDF 和 DOCX),您需要为每种类型调用该函数。或者,如果您知道所有附件都是您想要的文件类型,您可以像这样获取 所有 个附件:

$attachments = get_attached_media("images", $post->ID );

您的代码示例:

<?php 
$reports = array(   
   'post_type' => 'post' , 
   'posts_per_page' => 3,
   'category_name' => 'reports'); 
    
$q_reports = new WP_Query($reports);   
                
if($q_reports->have_posts()){
    while($q_reports->have_posts()){ 
        $q_reports->the_post();

        /* Get all attachments and loop through them to display the link & post title */
        $attachments = get_attached_media("");
        foreach ($attachments as $file){ ?>
            <a href='<?php echo $file["guid"]; ?>' ><?php echo $file["post_title"]; ?></a>
        <?php }

    endwhile; 
endif; ?>