User_FTW
User_FTW

Reputation: 524

Listing all attachments for particular category

I want to use this script to list all the attachments paths for posts of a 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();
    ?>

But the problem is it doesn't do anything unless I remove the 'category' arg, in which case it shows ALL attachment paths regardless. But I only want it for category 61.

I've triple checked and there are indeed posts that contain attachments in category 61.

What am I doing wrong?

Thanks in advance.

Upvotes: 0

Views: 1011

Answers (1)

Sumit
Sumit

Reputation: 1639

Category is not taxonomy for attachment post type. post and attachment are two different post types and category is attached to post and attachments are children of post.

So first get the all post in that category

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

Create the post IDs array so we can use in 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;
}

Now get all the children of all parent IDs

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

Display the attachments

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

Upvotes: 3

Related Questions