Get primary image for Wordpress post


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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

You need to login to post a comment.