WordPress 获取文章缩略图函数:get_the_post_thumbnail()完全指南

本文介绍了WordPress核心函数get_the_post_thumbnail(),用于获取和输出文章的特色图片。详细说明了其基本语法、三个参数(文章ID、图片尺寸、HTML属性)的用法,并提供了多种使用示例,包括基础用法、条件判断及在文章循环中的应用。

文章作者:曾凤祥
阅读时间: 164 分钟
更新时间:2026年3月4日

一、函数简介

get_the_post_thumbnail()是 WordPress 核心函数,用于获取和输出文章的”特色图片”(Featured Image)。

基本语法:

<?php echo get_the_post_thumbnail( $post_id, $size, $attr ); ?>

二、参数详解

1. 基本参数

<?php
// 基本用法 - 输出当前文章的缩略图
the_post_thumbnail();
// 或
echo get_the_post_thumbnail();

// 完整参数版本
echo get_the_post_thumbnail( 
    $post_id,     // 文章ID(可选,默认当前文章)
    $size,        // 图片尺寸(可选,默认'post-thumbnail')
    $attr         // HTML属性数组(可选)
);
?>

2. 参数详细说明

$post_id(整数|WP_Post对象)

// 获取指定文章的缩略图
echo get_the_post_thumbnail( 123 ); // 获取ID为123的文章的缩略图

// 在循环外获取当前文章的缩略图
global $post;
echo get_the_post_thumbnail( $post->ID );

// 在循环内
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        echo get_the_post_thumbnail( get_the_ID() );
    endwhile;
endif;

$size(字符串|数组)

WordPress 内置尺寸:

<?php
// 使用内置尺寸名称
echo get_the_post_thumbnail( null, 'thumbnail' );     // 150x150
echo get_the_post_thumbnail( null, 'medium' );        // 300x300
echo get_the_post_thumbnail( null, 'large' );         // 1024x1024
echo get_the_post_thumbnail( null, 'full' );          // 原始尺寸
echo get_the_post_thumbnail( null, 'post-thumbnail' ); // 默认(主题设置)

// 自定义尺寸(宽x高)
echo get_the_post_thumbnail( null, array( 800, 600 ) );

// 自定义尺寸名称(需在 functions.php 中注册)
// add_image_size( 'custom-size', 400, 300, true );
echo get_the_post_thumbnail( null, 'custom-size' );
?>

$attr(数组)

自定义 HTML 属性:

<?php
$attributes = array(
    'class'    => 'featured-image alignleft',
    'alt'      => get_the_title(),  // 使用文章标题作为alt文本
    'title'    => get_the_title(),
    'loading'  => 'lazy',          // 延迟加载
    'data-id'  => get_the_ID(),    // 自定义数据属性
    'sizes'    => '(max-width: 768px) 100vw, 50vw',
    'srcset'   => '',             // WordPress会自动生成响应式图片
);

echo get_the_post_thumbnail( null, 'large', $attributes );
?>

三、完整使用示例

1. 基础示例

<?php
// 示例1:最简单的用法
if ( has_post_thumbnail() ) {
    the_post_thumbnail(); // 直接输出
    // 或
    echo get_the_post_thumbnail();
}

// 示例2:带条件判断
if ( has_post_thumbnail() ) {
    echo '<div class="post-thumbnail">';
    the_post_thumbnail( 'large', array(
        'class' => 'img-responsive',
        'alt'   => get_the_title()
    ) );
    echo '</div>';
} else {
    // 没有缩略图时的备用图片
    echo '<div class="post-thumbnail">';
    echo '<img src="' . get_template_directory_uri() . '/images/default-thumb.jpg" alt="' . get_the_title() . '">';
    echo '</div>';
}
?>

2. 在文章循环中的使用

<?php
// 标准循环示例
if ( have_posts() ) :
    while ( have_posts() ) : the_post(); ?>
    
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            
            <?php if ( has_post_thumbnail() ) : ?>
                <div class="entry-thumbnail">
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                        <?php 
                        the_post_thumbnail( 'large', array(
                            'class' => 'post-thumb',
                            'alt'   => get_the_title(),
                            'title' => get_the_title()
                        ) ); ?>
                    </a>
                </div>
            <?php endif; ?>
            
            <div class="entry-content">
                <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                <?php the_excerpt(); ?>
            </div>
            
        </article>
        
    <?php endwhile;
endif;
?>

3. 获取缩略图URL(不输出img标签)

<?php
// 获取缩略图URL
$thumbnail_url = get_the_post_thumbnail_url( null, 'large' );
echo '<img src="' . esc_url( $thumbnail_url ) . '" alt="' . get_the_title() . '">';

// 获取不同尺寸的URL
$thumbnail_id = get_post_thumbnail_id( get_the_ID() );
$image_srcset = wp_get_attachment_image_srcset( $thumbnail_id, 'full' );
$image_sizes  = wp_get_attachment_image_sizes( $thumbnail_id, 'full' );

echo '<img src="' . esc_url( $thumbnail_url ) . '" 
            srcset="' . esc_attr( $image_srcset ) . '"
            sizes="' . esc_attr( $image_sizes ) . '"
            alt="' . get_the_title() . '">';
?>

4. 自定义尺寸和裁剪

<?php
// 在 functions.php 中注册自定义尺寸
add_action( 'after_setup_theme', 'mytheme_setup' );
function mytheme_setup() {
    add_theme_support( 'post-thumbnails' );
    
    // 注册自定义尺寸
    add_image_size( 'blog-list', 400, 300, true );      // 硬裁剪
    add_image_size( 'blog-single', 800, 500, false );   // 软裁剪
    add_image_size( 'blog-grid', 350, 350, array( 'center', 'center' ) ); // 从中心裁剪
}

// 在模板中使用自定义尺寸
echo get_the_post_thumbnail( null, 'blog-list', array(
    'class' => 'img-fluid rounded shadow'
) );

// 获取所有可用尺寸
$sizes = get_intermediate_image_sizes();
foreach ( $sizes as $size ) {
    echo $size . '<br>';
}
?>

5. 高级用法:响应式图片

<?php
// 自动生成响应式图片标签
if ( has_post_thumbnail() ) {
    $thumbnail_id  = get_post_thumbnail_id();
    $alt_text      = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true );
    
    echo wp_get_attachment_image( 
        $thumbnail_id, 
        array( 800, 600 ), 
        false, 
        array(
            'class'  => 'img-fluid',
            'alt'    => $alt_text ? $alt_text : get_the_title(),
            'sizes'  => '(max-width: 768px) 100vw, 50vw',
            'loading' => 'lazy'
        )
    );
}

// 使用 picture 元素
if ( has_post_thumbnail() ) {
    $thumbnail_id = get_post_thumbnail_id();
    $small = wp_get_attachment_image_src( $thumbnail_id, 'medium' );
    $large = wp_get_attachment_image_src( $thumbnail_id, 'large' );
    ?>
    <picture>
        <source media="(max-width: 768px)" srcset="<?php echo esc_url( $small[0] ); ?>">
        <source media="(min-width: 769px)" srcset="<?php echo esc_url( $large[0] ); ?>">
        <img src="<?php echo esc_url( $large[0] ); ?>" 
             alt="<?php the_title_attribute(); ?>" 
             class="featured-image">
    </picture>
    <?php
}
?>

6. 获取缩略图相关信息

<?php
if ( has_post_thumbnail() ) {
    $thumbnail_id = get_post_thumbnail_id();
    
    // 获取图片URL
    $image_url = get_the_post_thumbnail_url( null, 'full' );
    
    // 获取图片信息数组
    $image_data = wp_get_attachment_image_src( $thumbnail_id, 'full' );
    // $image_data[0] = URL
    // $image_data[1] = 宽度
    // $image_data[2] = 高度
    
    // 获取图片描述
    $image_caption = wp_get_attachment_caption( $thumbnail_id );
    
    // 获取图片描述(post_excerpt)
    $image_post = get_post( $thumbnail_id );
    $image_description = $image_post->post_excerpt;
    
    // 获取alt文本
    $image_alt = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true );
    
    // 获取图片元数据
    $image_meta = wp_get_attachment_metadata( $thumbnail_id );
    
    // 输出信息
    echo '<div class="image-info">';
    echo '<p>图片URL: ' . esc_url( $image_url ) . '</p>';
    echo '<p>尺寸: ' . $image_data[1] . ' × ' . $image_data[2] . 'px</p>';
    echo '<p>Alt文本: ' . esc_html( $image_alt ) . '</p>';
    if ( $image_caption ) {
        echo '<p>说明: ' . esc_html( $image_caption ) . '</p>';
    }
    echo '</div>';
}
?>

7. 在自定义查询中使用

<?php
// WP_Query 中使用
$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 6,
    'meta_key'       => '_thumbnail_id', // 只获取有缩略图的文章
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post(); ?>
        
        <div class="grid-item">
            <?php if ( has_post_thumbnail() ) : ?>
                <a href="<?php the_permalink(); ?>">
                    <?php the_post_thumbnail( 'medium', array(
                        'class' => 'grid-thumb',
                        'alt'   => get_the_title()
                    ) ); ?>
                </a>
            <?php endif; ?>
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        </div>
        
    <?php endwhile;
    wp_reset_postdata();
endif;
?>

四、常见问题解决

1. 缩略图不显示?

<?php
// 检查1:主题是否支持特色图片
add_theme_support( 'post-thumbnails' );

// 检查2:是否为文章类型启用
add_theme_support( 'post-thumbnails', array( 'post', 'page', 'product' ) );

// 检查3:在循环内使用
if ( have_posts() ) : while ( have_posts() ) : the_post();
    if ( has_post_thumbnail() ) {
        the_post_thumbnail();
    }
endwhile; endif;
?>

2. 自定义文章类型使用

<?php
// 注册自定义文章类型时启用缩略图
register_post_type( 'product', array(
    'public'      => true,
    'label'       => '产品',
    'supports'    => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
    // ... 其他参数
) );

// 在自定义文章类型模板中使用
if ( get_post_type() == 'product' ) {
    if ( has_post_thumbnail() ) {
        the_post_thumbnail( 'product-thumb', array(
            'class' => 'product-image',
            'alt'   => get_the_title() . ' - 产品图片'
        ) );
    }
}
?>

3. 性能优化

<?php
// 批量获取缩略图(减少查询)
function get_batch_post_thumbnails( $post_ids, $size = 'thumbnail' ) {
    $thumbnails = array();
    
    // 一次查询获取所有缩略图
    $thumb_ids = get_posts( array(
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'posts_per_page' => -1,
        'post_parent__in' => $post_ids,
        'fields'         => 'ids',
    ) );
    
    foreach ( $post_ids as $post_id ) {
        $thumbnail_id = get_post_thumbnail_id( $post_id );
        if ( $thumbnail_id ) {
            $thumbnails[$post_id] = wp_get_attachment_image_url( $thumbnail_id, $size );
        } else {
            $thumbnails[$post_id] = get_template_directory_uri() . '/images/default.jpg';
        }
    }
    
    return $thumbnails;
}

// 使用缓存
$cache_key = 'post_thumbnail_' . get_the_ID() . '_large';
$thumbnail = get_transient( $cache_key );

if ( false === $thumbnail ) {
    $thumbnail = get_the_post_thumbnail_url( null, 'large' );
    set_transient( $cache_key, $thumbnail, DAY_IN_SECONDS );
}

echo '<img src="' . esc_url( $thumbnail ) . '" alt="' . get_the_title() . '">';
?>

五、实用函数集合

1. 获取带链接的缩略图

<?php
function get_linked_post_thumbnail( $size = 'post-thumbnail', $class = '' ) {
    if ( ! has_post_thumbnail() ) {
        return '';
    }
    
    $thumbnail = get_the_post_thumbnail( null, $size, array(
        'class' => 'post-thumbnail ' . $class,
        'alt'   => get_the_title()
    ) );
    
    return sprintf(
        '<a href="%s" class="post-thumbnail-link" title="%s">%s</a>',
        esc_url( get_permalink() ),
        esc_attr( get_the_title() ),
        $thumbnail
    );
}

// 使用
echo get_linked_post_thumbnail( 'large', 'img-fluid' );
?>

2. 获取多尺寸图片

<?php
function get_responsive_post_thumbnail( $post_id = null, $class = '' ) {
    if ( ! has_post_thumbnail( $post_id ) ) {
        return '';
    }
    
    $post_id = $post_id ?: get_the_ID();
    $thumbnail_id = get_post_thumbnail_id( $post_id );
    
    $srcset = wp_get_attachment_image_srcset( $thumbnail_id, 'full' );
    $sizes  = wp_get_attachment_image_sizes( $thumbnail_id, 'full' );
    $url    = wp_get_attachment_image_url( $thumbnail_id, 'large' );
    $alt    = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true );
    
    return sprintf(
        '<img src="%s" srcset="%s" sizes="%s" alt="%s" class="%s" loading="lazy">',
        esc_url( $url ),
        esc_attr( $srcset ),
        esc_attr( $sizes ),
        esc_attr( $alt ?: get_the_title( $post_id ) ),
        esc_attr( 'responsive-thumb ' . $class )
    );
}
?>

3. 获取第一张图片作为缩略图

<?php
function get_first_image_as_thumbnail( $post_id = null, $size = 'thumbnail' ) {
    $post = get_post( $post_id );
    
    // 首先尝试获取特色图片
    if ( has_post_thumbnail( $post ) ) {
        return get_the_post_thumbnail( $post, $size );
    }
    
    // 如果没有特色图片,获取文章第一张图片
    $first_image = '';
    $content = $post->post_content;
    
    preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches );
    
    if ( isset( $matches[1][0] ) ) {
        $first_image = $matches[1][0];
        
        return sprintf(
            '<img src="%s" alt="%s" class="first-image-thumb">',
            esc_url( $first_image ),
            esc_attr( get_the_title( $post ) )
        );
    }
    
    // 返回默认图片
    return '<img src="' . get_template_directory_uri() . '/images/default-thumb.jpg" alt="' . get_the_title( $post ) . '">';
}
?>

六、最佳实践总结

场景推荐方法示例
简单输出the_post_thumbnail()直接输出缩略图
获取URLget_the_post_thumbnail_url()自定义img标签
获取数组wp_get_attachment_image_src()需要宽高信息
响应式wp_get_attachment_image()自动生成srcset
性能优化批量获取+缓存列表页使用
备用图片条件判断+默认图增强用户体验

代码片段快速参考:

<?php
// 1. 基本输出
if ( has_post_thumbnail() ) {
    the_post_thumbnail();
}

// 2. 带尺寸和属性
the_post_thumbnail( 'large', array(
    'class' => 'img-fluid',
    'alt'   => get_the_title(),
    'loading' => 'lazy'
) );

// 3. 获取URL
$thumb_url = get_the_post_thumbnail_url( null, 'large' );
echo '<img src="' . esc_url( $thumb_url ) . '">';

// 4. 响应式图片
echo wp_get_attachment_image( 
    get_post_thumbnail_id(), 
    'large', 
    false, 
    array( 'class' => 'responsive-img' ) 
);
?>

七、相关函数速查

  • has_post_thumbnail()– 检查是否有特色图片
  • get_the_post_thumbnail_url()– 获取缩略图URL
  • get_post_thumbnail_id()– 获取缩略图附件ID
  • wp_get_attachment_image()– 获取附件图片(更强大)
  • wp_get_attachment_image_src()– 获取图片src数组
  • wp_get_attachment_image_srcset()– 获取响应式srcset
  • the_post_thumbnail()– 直接输出(常用快捷方式)

重要提示:始终添加 alt属性以提高可访问性和SEO。使用响应式图片(srcset)优化移动端体验。在列表页面考虑使用延迟加载(loading=”lazy”)提升性能。

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

在AI里面继续讨论:

曾凤祥

曾凤祥

WordPress技术负责人
小兽WordPress凭借15年的WordPress企业网站开发经验,坚持以“为企业而生的WordPress服务”为宗旨,累计为10万多家客户提供高品质WordPress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。小兽WordPress能坚持多年,是因为我们一直诚信。

相关文章

如何让线上业务更上一层楼

还没有WordPress网站

还没有WordPress网站

不管你从事什么行业,WordPress都会为你提供一个专业的主题模板。在WordPress市场上有成千上万的免费主题,适合很多中小企业。

查看所有模板
已经有WordPress网站

已经有WordPress网站

小兽WordPress诚邀你一起学习WordPress,愿与各方携手升级改善您的WordPress网站,一起交流网站加速,网站优化等问题。

马上交个朋友
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部