Search code examples
phpwordpressrss

Wordpress rss feed issue on showing thumbnail


Below code not showing thumbnail from posts:

<?php
//grabs our post thumbnail image
    function get_first_image_url($html) {
        if (preg_match('/<img.+?src="(.+?)"/', $html, $matches)) {
            return $matches[1];
        }
    }
?>

Below code not showing thumbnail from posts:

<span class="rss-image">
    <?php echo '<img src="' . get_first_image_url($item -> get_content()) . '"/>'; ?>
</span>

Solution

  • Add this in functions.php

    function get_first_image_url($fetch_image) {
          global $fetch_image, $posts;
          $first_img = '';
          ob_start();
          ob_end_clean();
          $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $fetch_image, $matches);
          $first_img = $matches [1] [0];
    
          if(empty($first_img)){ //Defines a default image
            $first_img = "/images/default.jpg";
          }
          return $first_img;
        }
    

    and use this

    <span class="rss-image">
        <?php echo '<img src="' . get_first_image_url($item -> get_content()) . '"/>'; ?>
    </span>