Question: Wordpress media library custom taxonomy get image

Question

Wordpress media library custom taxonomy get image

Answers 1
Added at 2016-12-30 16:12
Tags
Question

I am using this code here to get images from media library using custom taxonomy. It gets the image url fine, but I want to get image id and title. How do I do that? This is what I have so far.

function get_images_from_media_library($cat) {
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' =>'image',
        'post_status' => 'inherit',
        'posts_per_page' => 6,
        'orderby' => 'rand',
        'tax_query' => array(
            array(
            'taxonomy' => 'gallery-category',
            'field' => 'slug',
            'terms' => $cat
            )
          )
        );
  $query_images = new WP_Query( $args );
  $images = array();
  foreach ( $query_images->posts as $image) {
    $images[]= $image->guid;
    echo $image->ID; // Returns image ID, but I need it in display_images_from_media_library function
  }
  return $images;
}
function display_images_from_media_library($cat) {
  $imgs = get_images_from_media_library($cat);
  foreach($imgs as $img) {
     $html .= '<img src="' . $img . '" alt="">';
  }
  return $html;
}
Answers to

Wordpress media library custom taxonomy get image

nr: #1 dodano: 2016-12-30 20:12

get_images_from_media_library() returns an array of image URLs therefore display_images_from_media_library() never has access to anything other than those URLs. If you wish to access the ID and title as well you'll need to make a couple of updates.

Inside get_images_from_media_library(), change this:

$images = array();
foreach ( $query_images->posts as $image) {
    $images[]= $image->guid;
    echo $image->ID; // Returns image ID, but I need it in display_images_from_media_library function
}
return $images;

To this:

return $query_images->posts;

The original code looped through the images and added their URLs to a new array. Here we're going to return the images in their original form.

Then we need to update the function that uses those images.

Change this:

$html .= '<img src="' . $img . '" alt="">';

To this:

$html .= '<img src="' . $img->guid . '" alt="">';

In my answer I've modified the code you've written to arrive at the desired result. I would however advise that you change the way you're retrieving the images in the first place. WP_Query isn't the most efficient way of handling it. Consider get_posts() instead.

Source Show
◀ Wstecz