wordpress中是有thumbnail缩略图这个概念的
但是有时候并不想手动去设置缩略图
于是就有了这段代码,这段代码可以使用正则表达式
去抓取文章第一个img标签
然后作为缩略图进行展示
但是我发现这种方法有一个弊端
就是无法像缩略图那样去灵活的裁剪(我做了裁剪的尝试,但是似乎没有生效)
很多时候加载的都是原图
原图很大,一定程度上也是消耗了带宽
使网站的加载速度变得更慢
而且展示时候,可能也只能通过css中的height和width去限制大小
代码部分:
function post_thumbnail()
{
global $post;
// Ensure $post exists
if (!$post) {
return;
}
// Get Featured Image (Thumbnail)
$img_id = get_post_thumbnail_id($post->ID);
$img_url = wp_get_attachment_image_src($img_id, 'pic-h');
if (!empty($img_url) && is_array($img_url)) {
$img_url = $img_url[0];
}
// If Featured Image Exists
if (!empty($img_url)) {
echo '<img src="' . esc_url($img_url) . '" alt="' . esc_attr(get_the_title()) . '" />';
return;
}
// Extract First Image from Post Content
$content = $post->post_content;
preg_match('/<img.*?src=["\'](.*?)["\'].*?>/i', $content, $matches);
if (!empty($matches[1])) {
$img_url = $matches[1];
$attachment_id = attachment_url_to_postid($img_url);
if ($attachment_id) {
$img_data = wp_get_attachment_image_src($attachment_id, 'pic-h');
foreach($img_data as $value){
echo $value . '<br>';
}
$img_url = $img_data[0];
echo $img_url;
}
echo '<img src="' . esc_url($img_url) . '" alt="' . esc_attr(get_the_title()) . '" />';
return;
}
echo '<img src="' . esc_url( get_template_directory_uri() ) . '/img/thumb-medium.png"';
}
调用的时候只要使用post_thumbnail()代替the_post_thumbnail()方法即可
文章评论