Generate all old PDF preview images with WordPress 4.7

WordPress 4.7 generates thumbnails for PDF files while uploading them in the media library, this is a really good thing especially if you have a site that uses PDF to publish some kind of contents (books, or lessons, documents or anything else) this can be really useful.

Even if, probably, you’ve already used┬áthe featured image to upload the first page of the PDF or a cover file.

To automatically create the images of all the PDF in your library, you have to trigger the file generation functions for all the file that you already have in your media library.

Here is a small script to process all your PDF files to generate thumbnails, there are two methods to call for each image:

1) wp_generate_attachment_metadata to generate the thumbnails
2) wp_update_attachment_metadata to store the new metadata generated in the database.

After running this script you will see the images in the media library an you can use the WordPress functions to show the attachments in your theme or plugin.

Place this file in the root. Run once and then remove it.

include 'wp-load.php';
include 'wp-admin/includes/image.php';
if ( !current_user_can( 'edit_others_pages' )) die("Not authorized.");
$attachments = $wpdb->get_results("select * from wp_posts where post_mime_type='application/pdf'");
if ($attachments) {
	foreach ($attachments as $attachment) {
		$filename = str_replace("http://".$_SERVER['HTTP_HOST'], $_SERVER['DOCUMENT_ROOT'], $attachment->guid);
		echo $filename."<br/>\n";
		$metadata = wp_generate_attachment_metadata($attachment->ID, $filename);
		wp_update_attachment_metadata($attachment->ID, $metadata);

Anything to say?

Comments with Facebook or below with WordPress

Sorry, WordPress comments are closed on old posts.