uploads - Dynamically create Permalinks for uploaded files?

admin2025-06-03  3

I have a custom page template, it lets users upload files using media_handle_upload() so everything is stored consistently in wp-content/uploads/20yy/mm/

I also store the filenames (and user_id, etc.) on a separate table tbl_files

I display a list of these files which should be available to download, and I want to do it using <a href=*nice looking dynamic permalink that doesn't say wp-content/uploads*>.

Is this possible? I'm thinking it should create a unique permalink during the upload process, then I can store that permalink on tbl_files, so I can just use that for my <a href>

I have a custom page template, it lets users upload files using media_handle_upload() so everything is stored consistently in wp-content/uploads/20yy/mm/

I also store the filenames (and user_id, etc.) on a separate table tbl_files

I display a list of these files which should be available to download, and I want to do it using <a href=*nice looking dynamic permalink that doesn't say wp-content/uploads*>.

Is this possible? I'm thinking it should create a unique permalink during the upload process, then I can store that permalink on tbl_files, so I can just use that for my <a href>

Share Improve this question asked Feb 11, 2019 at 1:57 RollorRollor 1291 gold badge4 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You could used a so called "virtual page".

A virtual page is a page which is not managed in the WordPress admin area. That means this page is not represents by a post, page or a custom post type.

There are different ways to create a virtual page, one way is to use a custom rewrite rule.

Example:

domain/download/123

// inform wordpress about the new url
add_filter( 'generate_rewrite_rules', function ( $wp_rewrite ) {
        $wp_rewrite->rules = array_merge(
        ['download/(\d+)/?$' => 'index.php?dl_id=$matches[1]'],
        $wp_rewrite->rules
    );
} );

// add dl_id to the list of WordPress query vars 
// so wordpress knows that variable
add_filter( 'query_vars', function( $query_vars ) {
    $query_vars[] = 'dl_id';
    return $public_query_vars;
} );


add_action( 'template_redirect', function() {
    $dl_id = intval( get_query_var( 'dl_id' ) );
    if ( $dl_id ) {
        // load the filename from the database and send the file to the browser 
        die;
    }
} );

A detailed explanation can be found in the article "How to Create a Virtual Page in WordPress" by Anh Tran on medium.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748906184a314702.html

最新回复(0)