schwdim
schwdim

Reputation: 193

Get all images attached to any post

I am getting a list of all the images the following way:

$the_query = new WP_Query( array(
  'post_type'       => 'attachment',
  'post_mime_type'  => 'image',
  'post_status'     => 'inherit',
  'posts_per_page'  => -1,
 ) );

But I'm trying to get only those who are uploaded to a post on my website.

Not images attached to a specific post but exclude those who aren't featured on any post.

Upvotes: 1

Views: 1330

Answers (2)

Purvik Dhorajiya
Purvik Dhorajiya

Reputation: 4880

All you have to do is paste the following code inside a loop.

$args = array(
        'post_parent'    => get_the_ID(), // your post id
        'post_type'      => 'attachment',
        'numberposts'    => -1, // show all
        'post_status'    => 'any',
        'post_mime_type' => 'image',
        'orderby'        => 'menu_order',
        'order'           => 'ASC'
   );

$images = get_posts($args);
if($images) { ?>
    <img src="<?php echo wp_get_attachment_url($image->ID); ?>" />
<?php
}
?>

Upvotes: 1

WPable.io
WPable.io

Reputation: 11

I think the post_mime_type is not correct.

$args = array(
    'post_type'  => 'attachment',
    'post_status'    => 'inherit',
    'post_mime_type' => 'image/gif',
);

$query = new WP_Query( $args );

Hope this helps!

Upvotes: 1

Related Questions