Site logo

[Support request] Force download of media file instead of opening in browser

Home Forums Support [Support request] Force download of media file instead of opening in browser

Home Forums Support Force download of media file instead of opening in browser

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #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,
    Shannon

    #2537360
    Ying
    Staff
    Customer Support

    Hi 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/

    #2537397
    Shannon

    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.”

    #2540538
    Shannon

    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.

    #2540543
    Ying
    Staff
    Customer Support

    I don’t think there’s a way to force download it in the same window in your case, unfortunately.

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.