列出特定类别的所有附件

Listing all attachments for particular category

我想使用此脚本列出特定类别帖子的所有附件路径:

<?php
    $args = array( 
        'post_type'     => 'attachment', 
        'numberposts'   => -1,
        'category'      => 61
    ); 
    $the_attachments = get_posts( $args );
    if ($the_attachments) {
        foreach ( $the_attachments as $post ) {
            setup_postdata($post);
            echo get_attached_file( $post->ID ) . "<br />";
        }
    } wp_reset_query();
    ?>

但问题是它什么都不做,除非我删除 'category' arg,在这种情况下它会显示所有附件路径。但我只想要类别 61。

我检查了三遍,确实有帖子包含类别 61 中的附件。

我做错了什么?

提前致谢。

类别不是 attachment post 类型的分类法。 postattachment 是两种不同的 post 类型,category 附加到 post 并且 attachments 是 children of [=15] =].

所以首先获取该类别中的所有 post

$cat_posts = get_posts(array(
    'category' => 61,
    'numberposts' => -1
));

创建 post ID 数组以便我们可以在 WP_Query

中使用
$parent_ids = array_map('get_post_ids', $cat_posts);

function get_post_ids($post_obj) {
    return isset($post_obj->ID) ? $post_obj->ID : false;
}

现在获取所有 parent 个 ID 的所有 children

$the_attachments = get_posts(array(
    'post_parent__in' => $parent_ids,
    'numberposts' => -1,
    'post_type' => 'attachment'
));

显示附件

if ($the_attachments) {
    foreach ( $the_attachments as $my_attachment ) {
        echo wp_get_attachment_image($my_attachment->ID);
    }
}

Note: post_parent__in is only available from version 3.6