post_thumbnail_html
云策文档标注
概述
post_thumbnail_html 是一个 WordPress 过滤器钩子,用于修改文章缩略图的 HTML 输出。它允许开发者自定义缩略图的显示内容,例如添加或修改属性。
关键要点
- 过滤器名称:post_thumbnail_html
- 参数:$html(缩略图 HTML 字符串)、$post_id(文章 ID)、$post_thumbnail_id(缩略图 ID)、$size(图像尺寸)、$attr(属性字符串或数组)
- 用途:在 get_the_post_thumbnail() 函数中调用,用于过滤生成的缩略图 HTML
- 注意事项:从 WordPress 5.9 开始,$attr 参数可能传递数组,需在类型声明中兼容以避免错误
代码示例
function wpdocs_addTitleToThumbnail( $html ) {
$id = get_post_thumbnail_id();
$alt_text = get_post_meta( $id, '_wp_attachment_image_alt', true );
$html = str_replace( 'alt=', 'title="' . esc_attr( $alt_text ) . '" alt=', $html );
return $html;
}
add_filter( 'post_thumbnail_html', 'wpdocs_addTitleToThumbnail' );
原文内容
Filters the post thumbnail HTML.
Parameters
$htmlstring-
The post thumbnail HTML.
$post_idint-
The post ID.
$post_thumbnail_idint-
The post thumbnail ID, or 0 if there isn’t one.
$sizestring|int[]-
Requested image size. Can be any registered image size name, or an array of width and height values in pixels (in that order).
$attrstring|array-
Query string or array of attributes.
Source
return apply_filters( 'post_thumbnail_html', $html, $post->ID, $post_thumbnail_id, $size, $attr );
Changelog
| Version | Description |
|---|---|
| 2.9.0 | Introduced. |
Skip to note 3 content
Curtiss Grymala
As of WP 5.9 (as far as I can tell), the
$attrparameter indicates it accepts astringorarray. If you are using parameter-typing in your methods/functions, and you previously indicated that your function should expect a string, you will see fatal errors due to this (as arrays are also sent, now). The change appears to have occurred here.Skip to note 4 content
João Carvalho
Add title attribute to post thumbnail:
function wpdocs_addTitleToThumbnail( $html ) { $id = get_post_thumbnail_id(); $alt_text = get_post_meta( $id, '_wp_attachment_image_alt', true ); $html = str_replace( 'alt=', 'title="' . esc_attr( $alt_text ) . '" alt=', $html ); return $html; } add_filter( 'post_thumbnail_html', 'wpdocs_addTitleToThumbnail' );