Created
December 10, 2018 14:14
-
-
Save fencermonir/2525d43b07b33bc272603c692f928010 to your computer and use it in GitHub Desktop.
Set First Image of the content as a featured image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*function to make the first image of the post as featured image*/ | |
function generate_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=1s"); | |
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', 'generate_featured_image'); | |
// Used for new posts | |
add_action('save_post', 'generate_featured_image'); | |
add_action('draft_to_publish', 'generate_featured_image'); | |
add_action('new_to_publish', 'generate_featured_image'); | |
add_action('pending_to_publish', 'generate_featured_image'); | |
add_action('future_to_publish', 'generate_featured_image'); | |
// remove first image from the content | |
function remove_first_image ($content) { | |
if (is_single()){ | |
$content = preg_replace("/<img[^>]+\>/i", "", $content, 1); | |
} | |
return $content; | |
} | |
add_filter('the_content', 'remove_first_image'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Glad to see that this code still works! Thank you!