Last active
January 25, 2021 16:45
-
-
Save dipakcg/85147678ae0cc0060f161fc0b944c60c to your computer and use it in GitHub Desktop.
📦 WordPress : Set first image as 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
// Get the first embedded image from the content | |
function catch_the_first_image() { | |
global $post, $posts; | |
$first_img = ''; | |
ob_start(); | |
ob_end_clean(); | |
$output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches); | |
if ( isset( $matches[1][0] ) ) { | |
$first_img = $matches[1][0]; | |
} | |
return $first_img; | |
} | |
// Set auto featured image | |
function set_featured_image() { | |
global $post; | |
$post_id = $post->ID; | |
if ( strlen( catch_the_first_image() ) >= 5 && get_the_post_thumbnail( $post_id ) == '' ) { | |
$image_url = get_site_url() . catch_the_first_image(); | |
$arrContextOptions = array( | |
"ssl" => array( | |
"verify_peer"=>false, | |
"verify_peer_name"=>false, | |
), | |
); | |
$upload_dir = wp_upload_dir(); | |
if ( is_ssl() ) { | |
$image_data = file_get_contents( $image_url, false, stream_context_create( $arrContextOptions ) ); | |
} | |
else { | |
$image_data = file_get_contents( $image_url ); | |
} | |
$filename = basename( $image_url ); | |
if( wp_mkdir_p( $upload_dir['path'] ) ) { | |
$file = $upload_dir['path'] . '/' . $filename; | |
} | |
else { | |
$file = $upload_dir['basedir'] . '/' . $filename; | |
} | |
file_put_contents( $file, $image_data ); | |
$wp_filetype = wp_check_filetype( $filename, null ); | |
$attachment = array( | |
'post_mime_type' => $wp_filetype['type'], | |
'post_title' => sanitize_file_name( $filename ), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
$attach_id = wp_insert_attachment( $attachment, $file, $post_id ); | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
$attach_data = wp_generate_attachment_metadata( $attach_id, $file ); | |
wp_update_attachment_metadata( $attach_id, $attach_data ); | |
set_post_thumbnail( $post_id, $attach_id ); | |
} | |
} | |
// Use it temporary to generate all featured images | |
add_action('the_post', 'set_featured_image'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment