我在下面使用了这段代码,虽然有点多,但它基本上是通过帖子缩略图、附加图像、内容中的图像,然后循环到每个类别的图像(这是我网站上的固定设置,因此在get_post_category_image
. 主要用途是通过最后一个函数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]*)"/\',
\'\',
$postOutput);
$postOutput = str_replace(array(\'class="alignright"\', \'class="alignleft"\'), \'\', $postOutput);
$postOutput = preg_replace(\'/title="([\\w-_]+)"/\',
\'\',
$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;
}