Last active
July 18, 2023 21:43
-
-
Save RadGH/6b58b136f19e52ce5ae3c72c1b7226b2 to your computer and use it in GitHub Desktop.
Import featured images from the post content for all posts on a WordPress site that do not have a featured image thumbnail
This file contains hidden or 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
<?php | |
/* | |
Plugin Name: RS Import Thumbnails | |
Description: Import thumbnails to your posts using the first image in the post content. To use this tool add to the end of your site url: ?rs_import_thumbnails_2023318_2330 | |
Version: 1.0 | |
Author: Radley Sustaire | |
Author URI: https://radleysustaire.com/ | |
*/ | |
// TEST THIS PLUGIN THOROUGHLY | |
// Results: | |
// 1. https://radleysustaire.com/s3/bbc95f/chrome | |
// 2. https://radleysustaire.com/s3/891141/chrome | |
// 3. https://radleysustaire.com/s3/d81801/chrome | |
// ?rs_import_thumbnails_2023318_2330 | |
function rs_import_thumbnails() { | |
// Get all posts that have no featured image (featured image is stored as metadata "_thumbnail_id") | |
$args = array( | |
'post_type' => 'post', | |
'posts_per_page' => 20, | |
'paged' => 1, // CHANGE THIS TO GO TO THE NEXT PAGE | |
'meta_query' => array( | |
array( | |
'key' => '_thumbnail_id', | |
'compare' => 'NOT EXISTS', | |
), | |
), | |
); | |
$query = new WP_Query( $args ); | |
// If no more posts, all done | |
if ( ! $query->have_posts() ) { | |
echo 'No more posts to process, all done!'; | |
} | |
$processed = 0; | |
$found_images = 0; | |
// Loop through posts | |
while ( $query->have_posts() ): $query->the_post(); | |
echo '<h3>Checking post <a src="' . get_the_permalink() . '">' . get_the_title() . '</a> (#'. get_the_ID() .')</h3>'; | |
$content = get_the_content(); // Get the post content | |
$pattern = '/<img[^>]+>/i'; // Regular expression pattern to match <img> tags | |
// Find the first <img> tag in the post content | |
preg_match( $pattern, $content, $matches ); | |
echo '<pre>'; | |
if ( ! empty( $matches ) ) { | |
$first_image = $matches[0]; // The first <img> tag found | |
// Extract the src attribute value using another regular expression | |
$src_pattern = '/src=[\'"]?([^\'" >]+)/i'; | |
preg_match( $src_pattern, $first_image, $src_matches ); | |
if ( ! empty( $src_matches ) && isset( $src_matches[1] ) ) { | |
// Attach the image to the post | |
$result = rs_attach_thumbnail_to_post( get_the_ID(), $src_matches[1] ); | |
if ( is_numeric($result) ) { | |
echo 'Image attached successfully! Image id #' . $result; | |
echo "\n\n"; | |
echo wp_get_attachment_image( $result, 'thumbnail' ); | |
}else{ | |
echo 'Failed to attach image to post, error:' . "\n\n" . $result; | |
} | |
} else { | |
echo 'Image was found, but src attribute was invalid:' . "\n\n" . esc_html($first_image); | |
} | |
} else { | |
// No <img> tag found | |
echo 'No image found.'; | |
} | |
echo '</pre>'; | |
endwhile; | |
exit; | |
} | |
if ( isset($_GET['rs_import_thumbnails_2023318_2330']) ) add_action( 'init', 'rs_import_thumbnails' ); | |
function rs_attach_thumbnail_to_post( $post_id, $image_url ) { | |
if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) { | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/media.php' ); | |
} | |
$filename = rs_get_image_filename_from_url( $image_url, get_the_title($post_id) ); | |
// Upload the image to the media library | |
$upload_file = wp_upload_bits( $filename, null, file_get_contents( $image_url ) ); | |
// Check if the upload was successful | |
if ( ! $upload_file['error'] ) { | |
// Prepare to create a new attachment using this metadata | |
$attachment = array( | |
'post_mime_type' => $upload_file['type'], | |
'post_title' => sanitize_file_name( $upload_file['file'] ), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
// Create the attachment | |
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id ); | |
// Set the attachment as the featured image | |
if ( ! is_wp_error( $attachment_id ) ) { | |
// Generate metadata and thumbnails for the attachment | |
$metadata = wp_generate_attachment_metadata( $attachment_id, get_attached_file( $attachment_id ) ); | |
if ( $metadata ) { | |
// Update the attachment's metadata | |
wp_update_attachment_metadata( $attachment_id, $metadata ); | |
} | |
// Attach the thumbnail | |
if ( set_post_thumbnail( $post_id, $attachment_id ) ) { | |
return $attachment_id; | |
}else{ | |
return 'attachment was uploaded, but set_post_thumbnail() failed'; | |
} | |
}else{ | |
return 'wp_insert_attachment() failed, attachment_id returned the error: ' . $attachment_id->get_error_message(); | |
} | |
}else{ | |
return 'wp_upload_bits() failed'; | |
} | |
} | |
function rs_upload_image_to_media_library( $image_url ) { | |
// Check if the required function is available | |
if ( ! function_exists( 'media_sideload_image' ) ) { | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/media.php' ); | |
} | |
// Download the image from the URL and upload it to the media library | |
$attachment_id = media_sideload_image( $image_url, 0 ); | |
if ( ! is_wp_error( $attachment_id ) ) { | |
return $attachment_id; | |
} | |
return false; | |
} | |
function rs_get_image_filename_from_url( $url, $post_title ) { | |
// Extract the path from the URL | |
$path = parse_url( $url, PHP_URL_PATH ); | |
// Get the filename from the path | |
$filename = basename( $path ); | |
$extension = pathinfo( $filename, PATHINFO_EXTENSION ); | |
// If the extracted filename is empty, use a generic filename with the ".jpg" extension | |
if ( empty( $extension ) ) { | |
$filename = sanitize_title_with_dashes($post_title); | |
$extension = rs_get_image_file_type( $url ); | |
if ( $extension ) { | |
$filename .= '.' . $extension; | |
}else{ | |
$filename .= '.jpg'; | |
} | |
} | |
return $filename; | |
} | |
function rs_get_image_file_type( $url ) { | |
// Get the MIME type of the content | |
$mime_type = mime_content_type( $url ); | |
// Check if the MIME type indicates a PNG file | |
if ( $mime_type === 'image/png' ) { | |
return 'png'; | |
} | |
// Default to 'jpg' if the MIME type is unknown or doesn't match JPG or PNG | |
return 'jpg'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment