Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save larodiel/8549e8666e4bd07a76310956c25fa87c to your computer and use it in GitHub Desktop.
Save larodiel/8549e8666e4bd07a76310956c25fa87c to your computer and use it in GitHub Desktop.
How to Set the First Post Image as a Featured Image (or Post thumbnail) Automatically From http://beginnersbook.com/2013/09/set-default-thumbnail-featured-fallback-image-wordpress-automatically/
function autogen_featured_img() {
global $post;
if (!has_post_thumbnail($post->ID)) {
$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);
}
}
}
}
/*This line is used to generate featured images for all old
posts. Remove this once the default images get generated
for all of the old posts*/
add_action('the_post', 'autogen_featured_img');
/* For new upcoming posts, leave them permanently*/
add_action('save_post', 'autogen_featured_img');
add_action('draft_to_publish', 'autogen_featured_img');
add_action('new_to_publish', 'autogen_featured_img');
add_action('pending_to_publish', 'autogen_featured_img');
add_action('future_to_publish', 'autogen_featured_img');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment