Get attached media only

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:

Read More
 $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

Related posts

Leave a Reply

2 comments

  1. 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);
    
  2. <?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>';
            }
    
        }
    }
    

    ?>