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.
1 Answer
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.