下面的函数用于显示第一段后的帖子缩略图。
add_filter( \'the_content\', \'insert_featured_image\', 20 );
function insert_featured_image( $content ) {
global $post;
if (has_post_thumbnail($post->ID)) {
$caption = \'<span class="image-caption">\'.get_the_post_thumbnail_caption( $post ).\'</span>\';
$img = \'<p>\'.get_the_post_thumbnail( $post->ID, \'full\' ).\'</p>\';
$content = preg_replace(\'#(<p>.*?</p>)#\',\'$1\'.$img . $caption, $content, 1);
}
return $content;
}
(感谢
Add 'if exists' to filter)
为了显示图像的标题,我对其进行了修改。
但是,如果特征图像没有标题,代码仍会输出空白span class=“图像标题”。
是否有方法包含if语句?
提前感谢!
最合适的回答,由SO网友:Waldo Rabie 整理而成
像这样的东西应该有用
add_filter( \'the_content\', \'insert_featured_image\', 20 );
function insert_featured_image( $content ) {
global $post;
if ( has_post_thumbnail($post->ID) ) {
$thumbnail_caption = get_the_post_thumbnail_caption( $post );
if ( $thumbnail_caption )
$caption = \'<span class="image-caption">\' . $thumbnail_caption . \'</span>\';
else
$caption = \'\'; // You can set this to whatever you want.
$img = \'<p>\' . get_the_post_thumbnail( $post->ID, \'full\' ) . \'</p>\';
$content = preg_replace( \'#(<p>.*?</p>)#\', \'$1\' . $img . $caption, $content, 1);
}
return $content;
}