hooks - how to create endpoint for downloading pdf files?

admin2025-01-07  3

I would like the logged-in user to be able to download the PDF file, but not to see the real path to the file. Additionally, in this PDF file, I enter information about the user name and date of download.

I created a new endpoint "download" to make the download address look like this: my-website/post-name/download/attached-id

function my_custom_endpoint() {
    add_rewrite_endpoint( 'download', EP_PERMALINK | EP_PAGES );
}  
add_action( 'init', 'my_custom_endpoint' );

but I don't know what the hook is to not load the page after calling this endpoint but to call my function and return the PDF file to the user.

I would like the logged-in user to be able to download the PDF file, but not to see the real path to the file. Additionally, in this PDF file, I enter information about the user name and date of download.

I created a new endpoint "download" to make the download address look like this: my-website.com/post-name/download/attached-id

function my_custom_endpoint() {
    add_rewrite_endpoint( 'download', EP_PERMALINK | EP_PAGES );
}  
add_action( 'init', 'my_custom_endpoint' );

but I don't know what the hook is to not load the page after calling this endpoint but to call my function and return the PDF file to the user.

Share Improve this question asked Dec 1, 2020 at 1:44 patryk siutapatryk siuta 311 bronze badge 1
  • Do not forget to refresh your permalinks: manually (Settings -> Permalinks -> Save Changes) or programatically (by flush_rewrite_rules()). If you choose function, use it carefully - it's heavy function – burlakvo Commented Jan 20, 2021 at 13:20
Add a comment  | 

1 Answer 1

Reset to default 1

A good action to hook in would be template_redirect. There you can query for your endpoint like this:

add_action('template_redirect', function() {
    global $wp_query;
    
    // Not your endpoint and not a page/post, we do nothing.
    if (!isset( $wp_query->query_vars['download']) || ! is_singular()) {
        return;
    }
    
    // Here goes your magic!
    […]
    
    // And probably a good idea to exit if you serve files.
    exit;
});

There's also a great tutorial about endpoints on Make WordPress.

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

最新回复(0)