Protect PDF Thumbnail Images with PDA

PDA plugins restrict access to all files, including PDF thumbnails, under the _pda folder by default. By rights, PDF thumbnails should follow the PDF files’ access permission.

Since complex checking leads to slower performance, i.e. image loading, we have not included that in our plugin’s features yet. That’s why PDF thumbnails are not accessible and display blank.

In order for the thumbnails to be shown once the PDF files are protected, simply put this code under your (child) theme’s functions.php file.

Requirements:

add_filter( 'pda_handle_attachment_id', 'pda_get_attachment_id', 10, 3 );

function pda_get_attachment_id( $attachment_id, $file_path, $mime ) {
   if ( $attachment_id ) {
      return $attachment_id;
   }

   // Only allow image file type.
   if ( false === $mime['type'] || false === strpos( $mime['type'], 'image' ) ) {
      return $attachment_id;
   }

   global $wpdb;
   $basename = wp_basename( $file_path );

   $query    = $wpdb->prepare(
      "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value LIKE %s",
      '_wp_attachment_metadata',
      "%$basename%"
   );
   $metadata = $wpdb->get_row( $query );

   if ( empty( $metadata ) ) {
      return $attachment_id;
   }

   return (int) $metadata->post_id;
}

Now all the PDF thumbnails will be accessible to anyone with access permission.

Limitation

If your site has thousands of PDF files, protecting PDF thumbnails might cause a performance issue, especially in the Media Library Grid View. In that case, you should not protect PDF thumbnails.

To do so, simply add the following code snippet to your (child) theme’s functions.php file.

Requirements:

add_filter('pda_original_rules', 'pda_allow_pdf', 10, 1);
add_filter('pda_folder_htaccess_rules', 'pda_allow_pdf', 10, 1);
function pda_allow_pdf($rules)
{
	$ignore_pdf_thumb_rule = 'RewriteCond %{REQUEST_URI} !^.*/.*-pdf-\d+x\d+.(jpg|png)$ [NC]';
	array_unshift($rules, $ignore_pdf_thumb_rule);
	return $rules;
}

Don’t forget to save our settings page for the rule to be implemented.

Lasted updated on June 25, 2021