In my opinion it is best to add an endpoint of the form mysite.com/pdf/<id>
or something similar to your like. That way you avoiding attaching the attachments to posts/pages or create a page for each pdf file with is redundant imo for your needs.
This is a very small and basic guide. You can modify to your needs.
First of all we add an endpoint matching all the request of the form mysite.com/pdf/<id>
. Note that you should flush the rewrite rules for the new endpoint to be working. You can do it manually by going Settings->Permalinks->Save Changes or by using flush_rewrite_rules
. It should be executed either on the shutdown
hook, or on plugin/theme (de)activation. Executing it on the init
hook is bad practice.
function my_endpoints() {
add_rewrite_endpoint( 'pdf', EP_ROOT);
}
add_action( 'init', 'my_endpoints' );
Then we use template_redirect
to handle the request.
function my_template_redirect() {
global $wp_query;
/* If it is a /pdf/<id> request then serve the file */
if(isset( $wp_query->query_vars['pdf'])){
// You can use sanitize_file_name also
$pdf_id = intval($wp_query->query_vars['pdf']);
/* Find the file and serve it */
}
return;
}
add_action( 'template_redirect', 'my_template_redirect' );