Reading time: 2 minutes
Hello, today we are going to see how we can automatically generate an image from the images we add in our posts or articles, without the need to select a featured image.
The first thing we need to do is open the WordPress control panel and select the theme file editor.
We open the theme editor and go to the page where our theme fills the main page (usually index.php
or home.php
). In my case, while navigating through the theme, I find it in content.php
In the template file, look for the code that generates the post excerpt. This could be a function like the_excerpt()
or a loop that iterates over the posts and displays the summarized content.
Just before or after the function that displays the excerpt, you can add the following code to get the image URL, crop it, scale it, and display it centered:
<?php //Show image $matches); isset($matches[1]) ? $matches[1] : '';
<?php //Mostrar imagen $matches = array(); preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', get_the_content(), $matches); $image_url = isset($matches[1]) ? $matches[1] : ''; if (!empty($image_url)) { $image = wp_get_image_editor($image_url); if (!is_wp_error($image)) { $image->resize(500, 300, true); $image->save($image->generate_filename('thumbnail')); $thumbnail_url = $image->get_image_src('thumbnail'); if (!empty($thumbnail_url)) { echo '<div style="text-align: center;">'; echo '<img src="' . esc_url($thumbnail_url) . '" alt="Thumbnail" />'; echo '</div>'; } } } ?>
I hope this helps, have a great day!