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="https://wordpress.stackexchange.com/questions/95271/. $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="https://wordpress.stackexchange.com/questions/95271/. $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.