Display the first image from a post in RSS feed

Here’s what I use in Dave’s WordPress Live Search to get the first image:

public static function firstImg( $post_content ) {
        $matches = array();
        $output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches );
        if ( isset( $matches[1][0] ) ) {
            $first_img = $matches[1][0];
        }

        if ( empty( $first_img ) ) {
            return '';
        }
        return $first_img;
    }

Leave a Comment