【问题标题】:How to retrieve an image from a post and display it before excerpt of a post in WordPress?如何从帖子中检索图像并在 WordPress 中的帖子摘录之前显示它?
【发布时间】:2013-03-27 12:51:59
【问题描述】:

我是 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>

好的, 如您所见,此代码 sn-p 显示帖子的摘录。

我会知道是否有可能在帖子中找到第一张图片,将其放入变量中并在摘录可视化之前将其显示在跨度(或其他一些 html 标记)中

Tnx

安德烈亚

【问题讨论】:

    标签: php content-management-system wordpress-theming wordpress


    【解决方案1】:

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

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

    并在循环中使用它:

        $post_excerpt = get_the_excerpt();
        echo firstImageExcerpt($post_excerpt);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 2011-01-11
      • 2018-01-26
      相关资源
      最近更新 更多