【问题标题】:Get attachment urls for a post - WordPress获取帖子的附件网址 - WordPress
【发布时间】:2013-01-20 23:27:49
【问题描述】:

我正在尝试创建一个 PDF 列表(每月创建的时事通讯)。我创建了一个名为“newsletters”的自定义帖子类型,并将其限制为仅支持“title”。

然后,我使用高级自定义字段插件向此帖子类型添加了文件上传按钮。因此,每个帖子都有一个标题和一个上传 pdf 的按钮。

然后我编写了以下函数来输出附件列表。

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;

}

但是 wp_get_attachment_url($id) 似乎不起作用。我认为这是因为我应该提供附件 ID 而不是帖子 ID。我在网上环顾四周,找不到明确的方法来查找特定帖子的附件 ID。

为了澄清每个帖子将只包含一个附件。

提前谢谢你

【问题讨论】:

    标签: php wordpress attachment custom-post-type


    【解决方案1】:

    此示例取自get_posts() Codex 页面

    $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 );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多