How to Automatically Set the Featured Image in WordPress

I am going to share quick easy snippet How to Automatically Set the Featured Image in WordPress that will set the featured image automatically by grabbing the first image of the post. You can select your own featured image as well. You just need to add this snippet to your theme’s function.php file.

[php]
<?php
function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
}
add_action(‘the_post’, ‘autoset_featured’);
add_action(‘save_post’, ‘autoset_featured’);
add_action(‘draft_to_publish’, ‘autoset_featured’);
add_action(‘new_to_publish’, ‘autoset_featured’);
add_action(‘pending_to_publish’, ‘autoset_featured’);
add_action(‘future_to_publish’, ‘autoset_featured’);
?>
[/php]

Source

Maan
Maan

21 year old designer, blogger and front-end developer. love to share creative design and inspiration.

Your email address will not be published. Required fields are marked *

div#stuning-header .dfd-stuning-header-bg-container {background-image: url(http://www.downgraf.com/wp-content/uploads/2017/04/login-back.jpg);background-size: cover;background-position: center center;background-attachment: scroll;background-repeat: no-repeat;}#stuning-header div.page-title-inner {min-height: 500px;}