Display Image for a category using get_categories, or show an image from any child post

This is possible with a filter on get_terms.

function grab_child_image($terms,$taxonomies,$args) {
  // var_dump($terms,$taxonomies,$args); // debug
  foreach ($terms as &$term) {
    $cp = new WP_Query(
      array (
        'cat' => $term->term_id,
        'fields' => 'ids',
        'ignore_sticky_posts' => true
      )
    );
    // var_dump($cp->posts); // debug
    if ($cp->have_posts()) {
      $attach = new WP_Query(
        array (
          'post_parent__in' => $cp->posts,
          'post_type' => 'attachment',
          'post_status' => 'inherit',
          'ignore_sticky_posts' => true,
          'posts_per_page' => 1
        )
      );
      if ($attach->have_posts()) {
        $term->image = wp_get_attachment_image($attach->posts[0]->ID);
      } else {
        $term->image="some other image";
      }
    }
  }
  return $terms;
}
add_filter('get_terms','grab_child_image',10,3);

$args = array('child_of'  => 1  );
$categories = get_categories($args);
foreach($categories as $category) { 
  echo '<p>Category:'. $category->name.' </p> ';
  echo '<p> Description:'. $category->description . '</p>';
  echo $category->image;
} 

remove_filter('get_terms','grab_child_image',10,3);

There are several queries in there, so add that filter only when you need it and remove the filter afterwards.

There are a number of related image functions that you could use instead, if wp_get_attachment_image() doesn’t work for your needs, and you can pass a $size parameter to wp_get_attachment_image()— second parameter– to get different image sizes. For example replace the line of code with this:

$term->image = wp_get_attachment_image($attach->posts[0]->ID, $size->full);

You can further alter the output of wp_get_attachment_image() by applying a filter to wp_get_attachment_image_attributes— for example, to add a class as done here.

Leave a Comment