Posted By

gn_themes on 05/28/11


Tagged

image wordpress images thumbnail wp thumb


Versions (?)

Wordpress post thumbnail


 / Published in: PHP
 

URL: http://ilovecode.ru/?p=209

Universal WordPress function for thumbnails

  1. /**
  2.  * Post thumbnail
  3.  *
  4.  * @global mixed $post Post object
  5.  * @param int $width Thumbnail width
  6.  * @param int $height Thumbnail height
  7.  * @param int $p Post/page ID
  8.  * @param bool $echo Echo/return
  9.  */
  10. function gn_post_thumbnail( $width = 150, $height = 150, $p = false, $echo = true ) {
  11.  
  12. // Config
  13. $default = get_template_directory_uri() . '/images/thumbnail.png'; // default image
  14. $timthumb = get_template_directory_uri() . '/lib/timthumb.php'; // path to timthumb script
  15. $meta = 'thumbnail'; // meta field name
  16.  
  17. global $post;
  18. $id = ( $p ) ? $p : $post->ID;
  19. $alt = get_the_title( $id );
  20.  
  21. // Get post attachments
  22. $attachments = get_posts( array(
  23. 'post_type' => 'attachment',
  24. 'numberposts' => 1,
  25. 'order' => 'ASC',
  26. 'post_status' => null,
  27. 'post_parent' => $id
  28. ) );
  29.  
  30. // Post thumbnail
  31. if ( has_post_thumbnail( $id ) ) {
  32. $image = wp_get_attachment_image_src( get_post_thumbnail_id( $id ), 'full' );
  33. $src = $image[0];
  34. }
  35.  
  36. // Meta field
  37. elseif ( get_post_meta( $id, $meta, true ) ) {
  38. $src = get_post_meta( $id, $meta, true );
  39. }
  40.  
  41. // First post image
  42. elseif ( $attachments ) {
  43. $src = $attachments[0]['guid'];
  44. }
  45.  
  46. // No matches, default image
  47. else {
  48. $src = $default;
  49. }
  50.  
  51. // Markup
  52. $return = '<img src="' . $timthumb . '?src=' . $src . '&amp;w=' . $width . '&amp;h=' . $height . '&amp;zc=1&amp;q=100" width="' . $width . '" height="' . $height . '" alt="' . $alt . '" />';
  53.  
  54. // Result
  55. if ( $echo ) echo $return;
  56. else return $return;
  57. }

Report this snippet  

You need to login to post a comment.