/**
* @author: wpreceipes
* @link: [1]: http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it
*/
function wpse18215_catch_that_image()
{
global $post, $posts;
$first_img = \'\';
ob_start();
ob_end_clean();
$output = preg_match_all( \'/<img.+src=[\\\'"]([^\\\'"]+)[\\\'"].*>/i\', $post->post_content, $matches );
$first_img = $matches[1][0];
//Defines a default image
if( empty( $first_img ) )
{
$first_img = \'/images/default.jpg\';
}
return $first_img;
}
示例:
echo catch_that_image();
或:
/**
* @author: Marcelo Mesquita
* @link: http://marcelomesquita.com/
* @param (string) $size - valid: \'thumbnail\', \'medium\', \'large\' or \'full_size\'
* @param (string) $add - any additional attributes for the html-img tag
*/
function wpse18215_the_thumb( $size = \'medium\', $add = \'\' )
{
global $wpdb, $post;
$thumb = $wpdb->get_row(
"SELECT ID,
post_title
FROM {$wpdb->posts}
WHERE post_parent = {$post->ID}
AND post_mime_type
LIKE \'image%\'
ORDER BY menu_order"
);
if( ! empty( $thumb ) )
{
$image = image_downsize( $thumb->ID, $size );
return "<img src=\'{$image[0]}\' alt=\'{$thumb->post_title}\' {$add} />";
}
}
示例:
echo wpse18215_the_thumb( \'medium\', \'class="alignleft" width="200" height="175"\' );
<人力资源>
Note: 无论如何,您都需要将模板中的调用包装到条件语句中:
if ( is_home() || is_front_page() ) { /* place the function call here */ }