首页 文章

如何从帖子中检索图像并在WordPress中的帖子摘录之前显示它?

提问于
浏览
0

我是PHP和WordPress的新手 .

我正在自定义WordPress模板,我将在我的主页的摘录帖子可视化中实现以下行为:

If a post contains immages (one or more), in the homepage post preview show at the beginnig a thumbnail of the first immage that is in the post, than show the excertp of the post

目前我有以下代码,在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>

好的,正如您可以看到此代码段显示帖子的摘录 .

我想知道是否有可能在帖子中找到第一个immage,将其放入变量并在摘录可视化之前显示它包含一个span(或其他一些html标记)

TNX

安德里亚

1 回答

  • 2

    您可以尝试使用下面的功能将您的第一张图像删除到开头

    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);
    

相关问题