1

I am using wp_query to get uploaded medias. Everything is working fine, but wp_query will return the medias with no post attached. This is not what I wanted. How can I exclude the unattached media from the wp_query?

This is my query arguments look like:

 $args = array(
  'post_type' => 'attachment',
  'post_status' => 'inherit',
  'posts_per_page' => -1,
  );
  $attachemnt = new WP_Query($args);

Is there any argument that can use for exclude the unattached media in wp_query class?

Thanks

2 Answers 2

5

All media (somewhat incorrectly) in the $wpdb->posts table will be "attachments" whether actually attached or not. "Attachments" that are actually attached will have a post_parent other than 0, so what you need are all of the attachments that have a 0 in the post_parent column, if I understand you.

$args = array(
  'post_type' => 'attachment',
  'post_status' => 'inherit',
  'posts_per_page' => -1,
  'post_parent__not_in' = array(0)
);
$attachment = new WP_Query($args);

var_dump($attachment->posts);
0
0
<?php if ( $post->post_type == **'post type name'** && $post->post_status == 'publish' ) {
    $attachments = get_posts( array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_parent' => $post->ID,
        'exclude'     => get_post_thumbnail_id()
    ) );

    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
            $class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
            $thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
            echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
        }

    }
}

?>

4
  • Thanks for the quick reply. But this is not i want, actually I don't have the 'post_parent' in the first place.
    – dev-jim
    Commented Mar 28, 2014 at 12:30
  • 1
    Please explain why this answer is helpful.
    – kaiser
    Commented Mar 28, 2014 at 12:40
  • @kaiser, do you mean me? No, I don't think this answer is helpful.
    – dev-jim
    Commented Mar 28, 2014 at 12:52
  • No, I was referring to @Chetan as he just posted code without explanation of what it does and how it is supposed to fix your issue.
    – kaiser
    Commented Mar 28, 2014 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.