0

I've got a function to display all images in the media library on a page. I would like to display the date of each image, but using get_the_date() only returns today's date.

Here is the code I'm using:

function get_images_from_media_library() {
$args = array(
    'post_type' => 'attachment',
    'post_mime_type' =>'image',
    'post_status' => 'inherit',
    'order'    => 'DESC'
        );
$query_images = new WP_Query( $args );
$images = array();
foreach ( $query_images->posts as $image) {
    $images[]= $image->guid;
}
return $images;
    }

function display_images_from_media_library() {

$imgs = get_images_from_media_library();
$html = '<div id="media-gallery">';

foreach($imgs as $img) {

    $html .= '<img src="' . $img . '" alt="" />';
    echo get_the_date('F j, Y');
}

$html .= '</div>';

return $html;

}

I could someone show me where I'm going wrong?

1
  • not necessarily related to the cause of your problem, but if you're using a function to run a wp_query() object, you might want it to also run wp_reset_query() at the end so it doesn't mess up other loops.
    – GhostToast
    Aug 15, 2013 at 13:23

1 Answer 1

1

get_the_date depends on the global $post variable. It is a bit hard to tell that that is the case but if you look at the source for get_the_date you'll see that it uses get_post and it assumes $post if no other parameters are given.

Your code never sets that global $post variable except for when your WP_Query initially runs. You need to refactor. I would return the post objects from get_images_from_media_library and construct a more standard Loop to process them.

I think this should be better.

function get_images_from_media_library() {
  $args = array(
    'post_type' => 'attachment',
    'post_mime_type' =>'image',
    'post_status' => 'inherit',
    'order'    => 'DESC'
  );
  $query_images = new WP_Query( $args );
  return $query_images;
}

function display_images_from_media_library() {
  $imgs = get_images_from_media_library();
  $html = '<div id="media-gallery">';
  global $post;
  if ($imgs->have_posts()) {
    while($imgs->have_posts()) {
      $imgs->the_post();
      $html .= '<img src="' . $post->guid . '" alt="" />';
      $html .=  get_the_date('F j, Y');
    }
  }
  $html .= '</div>';
  return $html;
}
echo display_images_from_media_library();
1
  • That works perfectly, and with a clear and concise explanation. Very much appreciated.
    – Paul Aston
    Aug 15, 2013 at 18:32

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.