0

I have seen another question located here, but it's not useful for my case; it's not working. Also, "RSS Feed Image" plugin is not working as desired.

I want to display the first image of the post in RSS feed.

Below is the code I am using for displaying thumbnail / featured images:

//Display TZ Thumbnail in RSS
function insertThumbnailRSS($content) {
    global $post;
    if ( has_post_thumbnail( $post->ID ) ) {
        $content = '' . get_the_post_thumbnail( $post->ID, 'thumbnail', array( 'alt' => get_the_title(), 'title' => get_the_title(), 'style' => 'float:left;margin: 20px' ) ) . '' . $content;
    }
    return $content;
}
add_filter('the_excerpt_rss', 'insertThumbnailRSS');
add_filter('the_content_feed', 'insertThumbnailRSS');

This one is working sweet, however anything I tried for the first image is not working at all. The least I could do was display the first image URL (not desired).

1

2 Answers 2

1

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;
    }
2
  • Thanks @Dave, but its not working. I added this with add_filter('the_excerpt_rss', 'firstImg'); but its not displaying anything in Feed Summary If I try this - it renders the URL of the first image but <img src> isn't working.
    – tushonline
    Commented Oct 15, 2013 at 16:57
  • This function just returns the URL of the first image. You'll have to write your own function and register it as a filter for the_excerpt_rss. Call this function in your code to get the URL of the first image,
    – Dave Ross
    Commented Oct 15, 2013 at 18:33
1

I used an outside library when I needed to do this. Might be overkill, but I ended up using it again in other areas of my plugin, so it made sense. Feed the post's content to this function, and hook it into those same filters you're using Eventually.

simple_html_dom.php is available here!

function first_image_extractor($description) {
    require_once('simple_html_dom.php');

    $post_html = str_get_html($description);
    $first_img = $post_html->find('img', 0);

    if($first_img !== null)
        return $first_img->src;

    return null;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.