Posted By

Wendelboe on 01/15/11


Tagged

image default wordpress gallery featured


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

qubestream
baires
anhonestboy
kirichev
to-ny


Get primary image for Wordpress post


 / Published in: PHP
 

If post has featured image, use it.. If not, pick out the first in the post.. Still not working? Stick with the default one..

  1. <?php
  2.  
  3. //Put this in functions.php
  4.  
  5. function get_primary_image($id, $size){
  6. $featured = wp_get_attachment_image_src( get_post_thumbnail_id($id), $size, false);
  7. if($featured){
  8. $childURL = $featured['0'];
  9. }else{
  10. $children = get_children(array('post_parent' => $id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => 1));
  11. reset($children);
  12. $childID = key($children);
  13. //$childURL = wp_get_attachment_url($childID);
  14. $childArray = wp_get_attachment_image_src($childID, $size, false);
  15. $childURL = $childArray['0'];
  16. if(empty($childURL)){
  17. $childURL = get_bloginfo('template_url')."/images/default.png";
  18. }
  19. }
  20. return($childURL);
  21. }
  22.  
  23.  
  24. //Run this in the loop (or any place you'd like - as long as you have an ID to feed it..)
  25. //First argument is the ID..
  26. //Second argument is the size.. It'll handle 'large', 'medium', 'thumbnail' or even
  27.  
  28. 'array(100, 100)'..
  29. get_primary_image(get_the_ID(), 'large');
  30.  
  31. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Wendelboe on January 17, 2011

[Update: Fixed call for ID, that would potentially output image for wrong post..]

You need to login to post a comment.