Site logo

Archived topic

get first image url from post and automaticaly add to featured image

5 replies · Started by danis on November 27, 2019

Viewing posts 1–6 of 6

Hi I'm struggling how to make the first image from post to featured image automatically (without a plugin "featured image from URL" )

Hi there,

may i ask why you're not just using the featured image in the editor?
You can set it to not display on the Single Post if that is the issue.

If not the plugin is the simplest way to go

Because I have a hundred more posts, it would take too much time to go through

i got some method but not working properly

so i add the php code to function.php

function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches);
$first_img = $matches[1][0];

if(empty($first_img)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}

and code for loop

if ( get_the_post_thumbnail($post_id) != '' ) {

echo ' __( 'Permalink to: ','archive' ), 'after' => '', 'echo' => false ) ) . '" rel="bookmark">';
the_post_thumbnail( 'full', array( 'itemprop'=>'image' ) );
echo '
';

} else {

echo '';
echo '<img src="';
echo catch_that_image();
echo '" alt="" />';
echo '
';

}

then i want to show the image inside-featured article,

reference yukonpromotions.com (this site using generatepress with featured img plugin)

so how to put the image & title together in frontpage?

advice please

This archived topic is closed to new replies.