Protect PDF Thumbnail Images with PDA Gold

Before version 3.1.2, PDF thumbnails are not protected by our PDA Gold. So even when you set the File Access Permission to everyone, the PDF thumbnails will not display.

At the moment, we’ve already checked and restricted access to all files under our protected folder including those PDF thumbnails. However, by rights, PDF thumbnails should follow the PDF access permission.

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

In order for the PDF thumbnails to follow the File Access Permission of PDF files, 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 February 7, 2021