Search code examples
phpcontent-management-systemwordpress-themingwordpress

How to retrieve an image from a post and display it before excerpt of a post in WordPress?


I am new in PHP and in WordPress.

I'm customizing a WordPress template and I would implement the following behavior in the excerpt posts visualization in my homepage:

If a post contains images (one or more), in the homepage post preview show at the beginning a thumbnail of the first image that is in the post, then show the excerpt of the post

At the moment I have the following code that, inside a WordPress loop, shows the excerpts of all posts on the homepage:

<!-- .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>

Ok, as you can see this code snippet shows the excerpt of a post.

I would know if is it possible to find the first image in the post, put it into a variable and show it inside a span (or some other HTML tag) before the excerpt visualization

Tnx

Andrea


Solution

  • You can try to use function below to remove your first image to the begining

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

    And use it in the LOOP:

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