You can use pdf.php
or a number of other specially-named template files as described birgire’s answer to show an attachment page specifically for PDFs, or use a generic attachment.php
page that includes conditional statements for the type of attachment (like the code in your question does).
Potential Conflict with Yoast SEO Plugin
Note that attachment template pages may not work if you have the Yoast SEO plugin installed. The default setting under Yoast SEO › Search Appearance › Media is to ‘Redirect attachment URLs to the attachment itself,’ which will override any attachment page template and directly link to the PDF, image file, or whatever you’ve uploaded.
How to Use Attachment Page Only for PDFs and Redirect Other Attachment Types Directly to their Files
Bonus: If you only want to show PDF attachment pages and redirect everything else to the attachment file, here’s some code to do that. (You’d put this in your functions.php
file.)
/**
* Redirect media attachment URLs to the attachment itself *unless* it's a PDF.
* See details: https://wordpress.stackexchange.com/questions/253226/
*/
add_action(
'template_redirect',
function() {
// Exit if this is not an attachment page.
if ( ! is_attachment() ) {
return;
}
// Exit (do nothing; do not redirect; use
// the pdf.php attachment template page)
// if this is a PDF attachment page.
if ( false !== stripos( get_post_mime_type(), 'pdf' ) ) {
return;
}
// Redirect all other attachment pages to
// their file. Use code '301' to indicate
// this is a permanent redirect.
if ( wp_get_attachment_url() ) {
wp_safe_redirect( wp_get_attachment_url(), '301' );
}
}
);