Posted By

Tate on 01/14/11


Tagged


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

qubestream
anhonestboy
kirichev


Get first image from Wordpress post


 / Published in: PHP
 

URL: http://www.rlmseo.com/blog/get-images-attached-to-post/

  1. function bdw_get_images() {
  2.  
  3. // Get the post ID
  4. $iPostID = $post->ID;
  5.  
  6. // Get images for this post
  7. $arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );
  8.  
  9. // If images exist for this page
  10. if($arrImages) {
  11.  
  12. // Get array keys representing attached image numbers
  13. $arrKeys = array_keys($arrImages);
  14.  
  15. /******BEGIN BUBBLE SORT BY MENU ORDER************
  16.   // Put all image objects into new array with standard numeric keys (new array only needed while we sort the keys)
  17.   foreach($arrImages as $oImage) {
  18.   $arrNewImages[] = $oImage;
  19.   }
  20.  
  21.   // Bubble sort image object array by menu_order TODO: Turn this into std "sort-by" function in functions.php
  22.   for($i = 0; $i < sizeof($arrNewImages) - 1; $i++) {
  23.   for($j = 0; $j < sizeof($arrNewImages) - 1; $j++) {
  24.   if((int)$arrNewImages[$j]->menu_order > (int)$arrNewImages[$j + 1]->menu_order) {
  25.   $oTemp = $arrNewImages[$j];
  26.   $arrNewImages[$j] = $arrNewImages[$j + 1];
  27.   $arrNewImages[$j + 1] = $oTemp;
  28.   }
  29.   }
  30.   }
  31.  
  32.   // Reset arrKeys array
  33.   $arrKeys = array();
  34.  
  35.   // Replace arrKeys with newly sorted object ids
  36.   foreach($arrNewImages as $oNewImage) {
  37.   $arrKeys[] = $oNewImage->ID;
  38.   }
  39.   ******END BUBBLE SORT BY MENU ORDER**************/
  40.  
  41. // Get the first image attachment
  42. $iNum = $arrKeys[0];
  43.  
  44. // Get the thumbnail url for the attachment
  45. $sThumbUrl = wp_get_attachment_thumb_url($iNum);
  46.  
  47. // UNCOMMENT THIS IF YOU WANT THE FULL SIZE IMAGE INSTEAD OF THE THUMBNAIL
  48. //$sImageUrl = wp_get_attachment_url($iNum);
  49.  
  50. // Build the <img> string
  51. $sImgString = '<a href="' . get_permalink() . '">' .
  52. '<img src="' . $sThumbUrl . '" width="150" height="150" alt="Thumbnail Image" title="Thumbnail Image" />' .
  53. '</a>';
  54.  
  55. // Print the image
  56. echo $sImgString;
  57. }
  58. }

Report this snippet  

You need to login to post a comment.