Humble code proposition: display first image as Featured when none is defined
-
Hello!
I thought this could interest more people, I am humbly offering you here a minor alteration I have brought to the Hueman theme, so that:
– when we have a post for which no Featured image has been defined
– the theme will simply take the first image embedded in the post (with img src), and make it the officially Featured image of that postPros: excellent for old blogs adopting the Hueman theme, whose posts were written without caring at all about attributing a special status (such as: Featured) to a special image.
Those old blog posts look very ugly with Hueman’s default “no image” display.
Better take their first image and make it the featured image. Now, they’re looking fresh and dandy!
Cons: one additional SQL query for every post to display in the page. Shouldn’t be much of an issue, hopefully.
I suspect there might be an additional faint load for the image processing, but I cannot tell if it would have a significant impact.
Lacking feature: to save to the post, as featured, the first chosen image, it would only have server impact once, on the first display. Beats me, no idea how it could be done, even if it would be awesome (I searched and tested, no plugin does it yet for already existing posts).I claim no credit, this code was offered to me by a very kind soul over the internet, called Noah, I simply tested that it works!
That’s why I’m sharing it here, with hopes to help, perhaps, other people. And – shamefully-, also with the hope to see it integrated into the official theme: this way I wouldn’t need to branch off to a child theme and give up on future Hueman updates ??The code, now:
in functions.php/* Noah Custom - Get first image of post /* ------------------------------------ */ function get_first_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 = "empty"; } return $first_img; }
in content.php
<?php elseif ( get_first_image() != 'empty' ): ?> <img src="<?php echo get_first_image(); ?>" alt="<?php the_title(); ?>" />
in content-featured.php
<?php elseif ( get_first_image() != 'empty' ): ?> <img src="<?php echo get_first_image(); ?>" alt="<?php the_title(); ?>" />
in content-standard.php
<?php elseif ( get_first_image() != 'empty' ): ?> <img src="<?php echo get_first_image(); ?>" alt="<?php the_title(); ?>" />
That’s it!
I just remembered to have to add it to the “you might also like” miniatures, but it’s nothing crazy to add, I just haven’t tested that addition yet.I hope this change suggestion might be of help to some people in the future ??
(And, who knows, maybe that could go to core, I can dream!)
- The topic ‘Humble code proposition: display first image as Featured when none is defined’ is closed to new replies.