I’m using this code below, it’s quite a bit, but it basically loops through post thumbnail, attached image, image in content and then to an image per category (which is a fixed set on my site, hence the naming scheme of the images in get_post_category_image
. The main usage is through the last function, simply do echo get_post_image()
:
function get_post_content_thumbnail($num, $width="", $height="") {
$content = get_the_content();
$count = substr_count($content, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
$imgBeg = strpos($content, '<img', $start);
$post = substr($content, $imgBeg);
$imgEnd = strpos($post, '>');
$postOutput = substr($post, 0, $imgEnd+1);
$postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"https://wordpress.stackexchange.com/",
'',
$postOutput);
$postOutput = str_replace(array('class="alignright"', 'class="alignleft"'), '', $postOutput);
$postOutput = preg_replace('/title="([\w-_]+)"https://wordpress.stackexchange.com/",
'',
$postOutput);
$image[$i] = $postOutput;
$start=$imgEnd+1;
}
if(isset($image) && stristr($image[$num],'<img')) {
return str_replace('<img ', '<img ' . image_hwstring($width, $height), $image[$num]);
}
}
function get_post_attachment_thumbnail($width="", $height="") {
$files = get_children('post_parent=".get_the_ID()."&post_type=attachment&post_mime_type=image');
if($files) {
$keys = array_reverse(array_keys($files));
$j=0;
$attachment_id = $keys[$j];
$image = image_downsize($attachment_id, 'thumbnail');
$image[0] = str_replace('http://yoast.com', 'http://cdn.yoast.com', $image[0]);
return '<img src="' . $image[0] . '" alt="" ' . image_hwstring($width, $height) . '/>';
}
}
function get_post_category_image($p_id=null, $width="", $height=""){
global $post_id, $top_category;
if (!$p_id)
$p_id = $post_id;
if ( isset($top_category) )
return $top_category;
$post_categories = get_the_category( $p_id );
$slug = count($post_categories) ? $post_categories[0]->slug : '';
if ($slug && file_exists(TEMPLATEPATH . '/img/post-img/'.$slug.'.png')){
return '<img ' . image_hwstring($width, $height). ' src="' . get_bloginfo('template_url') . '/img/post-img/'.$slug.'.png" alt="'.$post_categories[0]->cat_name.'"/>';
} else {
return '<img ' . image_hwstring($width, $height). ' src="' . get_bloginfo('template_url') . '/img/post-img/default.jpg" alt=""/>';
}
}
function get_post_image($string_size="post-thumbnail", $width=0){
if ( has_post_thumbnail() ) :
return get_the_post_thumbnail(NULL, $string_size, array('title'=>''));
elseif( $attached_image = get_post_attachment_thumbnail($width)):
return $attached_image;
elseif( $post_content_thumbnail = get_post_content_thumbnail(1, $width)):
return $post_content_thumbnail;
else:
return get_post_category_image(NULL, $width);
endif;
}