我是PHP和WordPress新手。
我正在定制一个WordPress模板,我将在我的主页上实现以下行为:
如果一篇文章包含图片(一张或多张),在首页的文章预览中在文章开头显示第一张图片的缩略图,然后显示文章的摘录
目前,我有以下代码,在WordPress循环中,显示主页上所有帖子的摘录:
<!-- .entry-summary -->
<?php else : ?>
<div class="entry-content">
<?php the_excerpt(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'admired' ) . '</span>', 'after' => '</div>' ) ); ?>
</div>
好的,如您所见,这段代码片段显示了一篇文章的摘录。
我想知道是否有可能在帖子中找到第一个图像,将其放入变量并在摘录可视化之前将其显示在span(或其他HTML标签)中
Tnx
Andrea
您可以尝试使用下面的函数将您的第一张图像移到开始
function firstImageExcerpt($post_excerpt) {
$reg_exp= '/<img.+src=[''"]([^''"]+)[''"].*>/i';
preg_match_all($reg_exp, $post_excerpt, $matches);
$first_img = $matches[0][0];
$post_excerpt = str_replace($first_img, '', $post_excerpt);
$post_excerpt = $first_img . $post_excerpt;
return $post_excerpt;
}
并在LOOP中使用:
$post_excerpt = get_the_excerpt();
echo firstImageExcerpt($post_excerpt);