Skip to content

Instantly share code, notes, and snippets.

@joychetry
Created April 20, 2020 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joychetry/400bfd919cac4a2c03e807b7ab665abf to your computer and use it in GitHub Desktop.
Save joychetry/400bfd919cac4a2c03e807b7ab665abf to your computer and use it in GitHub Desktop.
Pull First Image as Featured Image if Featured Image is NA
/* START - Pull First Image as Featured Image if Featured Image is NA */
function crowwwn_auto_featured_image() {
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);
}
}
}
}
// Use it temporary to generate all featured images
add_action('the_post', 'crowwwn_auto_featured_image');
// Used for new posts
add_action('save_post', 'crowwwn_auto_featured_image');
add_action('draft_to_publish', 'crowwwn_auto_featured_image');
add_action('new_to_publish', 'crowwwn_auto_featured_image');
add_action('pending_to_publish', 'crowwwn_auto_featured_image');
add_action('future_to_publish', 'crowwwn_auto_featured_image');
/* END - Pull First Image as Featured Image if Featured Image is NA */
@paaljoachim
Copy link

Thank you for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment