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…

Dicembre 13, 2016

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);
	}
}

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Recommended

WP Gutenberg notes

Collection of notes and thoughts on Wordpress Gutenberg blocks development.

Gennaio 9, 2023

Test page for Bright Links plugin

To test the plugin hover your mouse to a link, or tap the link on mobile device.

Dicembre 4, 2022

Updating a metabox after Gutenberg updates

When press on "Update" refresh a custom metabox under gutenberg editor.

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

Febbraio 8, 2020

Two post types share the same taxonomy in WordPress

Sharing a WordPress taxonomy between two post types is useful especially if you want to create a relation between different…

Novembre 14, 2019

Modify the language attribute based on category in WordPress

How to modify the language attribute in your Wordpress theme using a specific value

Novembre 7, 2019