0

I want to show the last 12 images that were published with articles on my front page. This is the code to get the latest 12 uploaded images, but i want to show only the ones attached to a post (single). Any idea?

<?php

    $args = array(
        'post_type' => 'attachment',
        'numberposts' => 12,
        'post_status' => inherit,
    );

    $attachments = get_posts( $args );
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
        echo '<li>';
        echo wp_get_attachment_image( $attachment->ID, array('90', '90') );
        echo '</li>';
        }
    }

?>

1 Answer 1

1

I haven't tested this but logically... ;)

Images attached to posts should have post_parent greater than zero, with the most recent posts (post parents) having the highest ID, though longstanding draft posts might throw this off a bit. So, if you order by the post_parent descending you should have the top 12 attachments associated with your posts.

$args = array(
    'post_type' => 'attachment',
    'posts_per_page' => 12, // numberposts is long since deprecated in WP_Query
    'post_status' => inherit,
    'orderby' => 'post_parent',
    'order' => 'DESC'
);

Now, if you are getting attachments from pages and CPTs you will need a more complicated solution and will have to query your posts for IDs,then pull attachments.

Any idea how to get the link of the parent post/page? I tried "get_permalink( $post->post_parent )" but it gives me only the latest post. (From a comment below)

The way your code is written, the $post global isn't going to be set. What you need is $attachment->post_parent. Or, my preference, skip the get_posts() wrapper and use WP_Query itself:

$args = array(
    'post_type' => 'attachment',
    'posts_per_page' => 12, // numberposts is long since deprecated in WP_Query
    'post_status' => 'inherit',
    'orderby' => 'post_parent',
    'order' => 'DESC'
);
$attachments = new WP_Query( $args );
if ( $attachments->have_posts() ) {
    while ( $attachments->have_posts() ) {
      $attachments->the_post();
      var_dump($post->post_parent); // now it is set
      echo '<li>';
      echo wp_get_attachment_image( $post->ID, array('90', '90') );
      echo '</li>';
    }
}
4
  • This works for pages, too :) Oct 18, 2015 at 16:25
  • Yes, pages, posts, CPTs are all basically the same thing in the database, just "categorized" differently.
    – s_ha_dum
    Oct 18, 2015 at 16:27
  • Any idea how to get the link of the parent post/page? I tried "get_permalink( $post->post_parent )" but it gives me only the latest post. Oct 18, 2015 at 16:36
  • @HenningFischer : see the edit
    – s_ha_dum
    Oct 18, 2015 at 17:09

Your Answer

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

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