1

I have hundreds of PDFs that are linked throughout my site, and these PDFs all have a unique document number and revisions. e.g. 902367 version I

What I would like to do is have a defined slug for each document, such as mysite.com/902367/ that would link directly to the document. Redirects are one way to accomplish this, but even with REGEX this would be sloppy and less than ideal.

I found one other question explaining that if your theme had an attachments file, that any attachments uploaded to that page would fall under the same category. However, that does not really apply to my situation as I am not trying to assign PDFs to a category, or a page, but rather essentially making them a page themselves. Is creating a pseudo page for the document the cleanest way to accomplish this?

What would be the most eloquent way of applying WordPress slug functionality to my PDFs?

  • I would use add_rewrite_endpoint and match something like mysite.com/pdf/<id> and then use template_redirect to serve the requested file. – Laxmana Apr 4 '17 at 13:42
  • I am working on getting my head around how that rewrite works, but I may just have to try it out on my staging to see how it works. Thanks. – fwho Apr 4 '17 at 13:51
1

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' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.