- This topic has 4 replies, 2 voices, and was last updated 2 years, 6 months ago by
Ying.
-
AuthorPosts
-
February 17, 2023 at 10:49 am #2537176
Shannon
I’ve been looking in the forum for a solution to force the download of a media file (in this case an audio file) instead of opening in another browser window.
The file is hosted with a separate cloud service. In speaking with the cloud service’s support they noted: “You can use ?download query parameter to force the download of your files by appending ?download=true to the URL.”
The download link has been created using a buttons block inside an element. The button block populates dynamically.
I tried using the “download” custom atttribute to the buttons and button block but didn’t have any luck.
Might a hook work in this case? I found a similar response to a question here: https://generatepress.com/forums/topic/customizing-attachment-pages/
Thanks,
ShannonFebruary 17, 2023 at 2:18 pm #2537360Ying
StaffCustomer SupportHi Shannon,
1. Add an additional CSS class to the button block, eg.
download-button
.
https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/2. Add this PHP snippet:
add_filter( 'render_block', function( $block_content, $block ) { if ( ! empty( $block['attrs']['className'] ) && 'download-button' === $block['attrs']['className'] ) { $block_content = str_replace('<a ', '<a download ', $block_content); } return $block_content; }, 10, 2 );
Adding PHP: https://docs.generatepress.com/article/adding-php/
February 17, 2023 at 3:02 pm #2537397Shannon
Thank you Ying.
Your solution of course did as you wanted. The class is added and the rewrite happens however the file still opens in a separate browser window.
I did a little digging and could it not be working as expected due to the actual file being hosted elsewhere? A quote from an article:
“The download attribute only works for same-origin URLs. So if the href is not the same origin as the site, it won’t work. In other words, you can only download files that belongs to that website. This attribute follows the same rules outline in the same-origin policy.”
February 20, 2023 at 4:36 pm #2540538Shannon
Just wanted to see if there might be another approach to this using a hook. As I mentioned in the previous response the file still opens in a separate window.
Thanks.
February 20, 2023 at 4:57 pm #2540543Ying
StaffCustomer SupportI don’t think there’s a way to force download it in the same window in your case, unfortunately.
-
AuthorPosts
- You must be logged in to reply to this topic.