简体   繁体   English

获取帖子的附件网址-WordPress

[英]Get attachment urls for a post - WordPress

I am trying to create a list of PDFs (newsletters created each month). 我正在尝试创建PDF列表(每月创建的新闻通讯)。 I have created a custom post type named 'newsletters' and restricted it to only supporting a 'title'. 我创建了一个名为“ newsletters”的自定义帖子类型,并将其限制为仅支持“ title”。

I have then used the advanced custom fields plugin to add a file upload button to this post type. 然后,我使用高级自定义字段插件将文件上传按钮添加到此帖子类型。 Therefore each post has a title and a button to upload the pdf. 因此,每个帖子都有一个标题和一个用于上载pdf的按钮。

I have then written the below function to output the list of attachments. 然后,我编写了以下函数来输出附件列表。

function list_newsletters(){

    $args = array( 'post_type' => 'newsletters' );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
        $permalink = get_permalink();
        $title = get_the_title();
        $id = get_the_ID();
        $attachment = wp_get_attachment_url($id);
        echo '<li><a href="'.$attachment.'">'.$title.'</li>';
    endwhile;

}

However the wp_get_attachment_url($id) doesn't seem to work. 但是wp_get_attachment_url($ id)似乎不起作用。 I think this is because I am supposed to be supplying the attachment ID rather than the post ID. 我认为这是因为我应该提供附件ID而不是帖子ID。 I have looked around online and cannot find a clear way of finding the attachment ID for a specific post. 我已经在网上四处张望,找不到找到特定帖子的附件ID的明确方法。

Just to clarify each post will only contain one attached file. 只是为了澄清每个帖子将只包含一个附件。

Thank you in advance 先感谢您

This example taken from the get_posts() Codex page 此示例摘自get_posts()法典页面

$attachments = get_posts(array( 
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' =>'any',
    'post_parent' => $post->ID
));

if ($attachments) {
    foreach ( $attachments as $attachment ) {
        echo apply_filters( 'the_title' , $attachment->post_title );
        the_attachment_link( $attachment->ID , false );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM