You can achieve this in WordPress by using custom rewrite rules.
Use this code inside theme’s function.php file or inside a plugin.
// 1- Create a custom query var
add_filter( 'query_vars', function ( $query_vars ) {
$query_vars[] = 'my_pdf_file';
return $query_vars;
});
// 2- Add a custom rewrite rule.
// NOTE: rewrite rules must be flushed for this rule to work.
// You can flush rewrite it by saving permalinks from dashboard.
add_action('init', function (){
add_rewrite_rule('^pdf-files/([a-zA-Z0-9 _\-]+\.pdf)$','index.php?my_pdf_file=$matches[1]' );
});
// 3- Find and display the PDF file when a pdf file link is visited.
add_action('template_redirect', function () {
$pdf_file_name = get_query_var('my_pdf_file');
// Don't do anything if no file name is supplied
if(! $pdf_file_name) {
return;
}
// Create the file path with the supplied name.
$pdf_file_path = \WP_CONTENT_DIR . '/customUploads/' . $pdf_file_name;
// Show 404 page if invalid file name is supplied
if(! is_file($pdf_file_path)) {
global $wp_query;
$wp_query->set_404();
return;
}
// Read and display the PDF file
header("Content-type: application/pdf");
readfile($pdf_file_path);
exit;
});
Don’t forget to save permalinks from “permalinks settings” page on WordPress dashboard to flush rewrite rules after using the above code.