Custom folder with PDF files (not in WP Library) - Create url for each file

I have a folder mywebsite.com/wp-content/customUploads which contains hundreds of pdf files.

At this point the url to see a pdf file is for example: mywebsite.com/wp-content/customUploads/myfile.pdf

My goal is to have a url for each PDF file like: mywebsite.com/pdf-files/myfile.pdf

So if a user request the above url, the website will load the pdf file.

Is there a way to request the url:

  • mywebsite.com/pdf-files/myfile.pdf

and this url is translated to the following, so the file could be loaded correctly?

  • mywebsite.com/wp-content/customUploads/myfile.pdf

Topic url-rewriting pdf Wordpress

Category Web


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.