Return to Snippet

Revision: 46988
at May 28, 2011 19:37 by gn_themes


Initial Code
/**
 * Post thumbnail
 *
 * @global mixed $post Post object
 * @param int $width Thumbnail width
 * @param int $height  Thumbnail height
 * @param int $p Post/page ID
 * @param bool $echo Echo/return
 */
function gn_post_thumbnail( $width = 150, $height = 150, $p = false, $echo = true ) {

	// Config
	$default = get_template_directory_uri() . '/images/thumbnail.png'; // default image
	$timthumb = get_template_directory_uri() . '/lib/timthumb.php'; // path to timthumb script
	$meta = 'thumbnail'; // meta field name

	global $post;
	$id = ( $p ) ? $p : $post->ID;
	$alt = get_the_title( $id );

	// Get post attachments
	$attachments = get_posts( array(
		'post_type' => 'attachment',
		'numberposts' => 1,
		'order' => 'ASC',
		'post_status' => null,
		'post_parent' => $id
		) );

	// Post thumbnail
	if ( has_post_thumbnail( $id ) ) {
		$image = wp_get_attachment_image_src( get_post_thumbnail_id( $id ), 'full' );
		$src = $image[0];
	}

	// Meta field
	elseif ( get_post_meta( $id, $meta, true ) ) {
		$src = get_post_meta( $id, $meta, true );
	}

	// First post image
	elseif ( $attachments ) {
		$src = $attachments[0]['guid'];
	}

	// No matches, default image
	else {
		$src = $default;
	}

	// Markup
	$return = '<img src="' . $timthumb . '?src=' . $src . '&amp;w=' . $width . '&amp;h=' . $height . '&amp;zc=1&amp;q=100" width="' . $width . '" height="' . $height . '" alt="' . $alt . '" />';

	// Result
	if ( $echo ) echo $return;
	else return $return;
}

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

Initial Description
Universal WordPress function for thumbnails

Initial Title
Wordpress post thumbnail

Initial Tags
image, wordpress, images

Initial Language
PHP