open all .docs in word online

Hey I’m trying to make all .doc/docx .xls/xlsx files open in office online.

This would mean that every link to a .doc

Read More
http://mywebsite.com/wp-content/uploads.link.doc

would have to instead point to the office online preview link

https://view.officeapps.live.com/op/view.aspx?src=http://mywebsite.com/wp-content/uploads/link.doc

I’m not even sure how to go about doing this? Any help would be greatly appreciated!

Thanks!

Related posts

Leave a Reply

1 comment

  1. I’m not sure this question is WordPress-related. It sounds like it might be handled via .htaccess redirect, or a browser extension.

    That said: you could try to use the wp_get_attachment_url filter, that is applied to the URL returned by wp_get_attachment_url().

    For example:

    function wpse95271_filter_wp_get_attachment_url( $url ) {
        if ( 0 === stripos( strrev( $url ), 'cod.' ) ) {
            // This is a Word doc; modify the URL
            $url = 'https://view.officeapps.live.com/op/view.aspx?src=' . $url;
        }
        return $url;
    }
    add_filter( 'wp_get_attachment_url', 'wpse95271_filter_wp_get_attachment_url' );
    

    (This is completely untested, and presented as an example only.)

    Edit

    a) how can I add .docx, .xls, .xlsx?

    Just extend the conditional. Here’s an example, abstracted for clarity:

    function wpse95271_filter_wp_get_attachment_url( $url ) {
        // Using a simple ternary expression;
        // there may be better ways, such as
        // an array of doc extensions, and a
        // foreach loop, etc
        $is_msoffice_doc = (
            0 === stripos( strrev( $url ), 'cod.' ) ||
            0 === stripos( strrev( $url ), 'xcod.' ) ||
            0 === stripos( strrev( $url ), 'slx.' ) ||
            0 === stripos( strrev( $url ), 'xslx.' ) ? true : false
        );
        if ( $is_msoffice_doc ) {
            // This is an Office doc; modify the URL
            $url = 'https://view.officeapps.live.com/op/view.aspx?src=' . $url;
        }
        return $url;
    }
    add_filter( 'wp_get_attachment_url', 'wpse95271_filter_wp_get_attachment_url' );
    

    b) instead of replacing the url can I add a link next to the normal download link that says “open online” with a link to this?

    Just build your own link in your template, appending the attachment URL to your base URL, as done in the above filter.