How can I change the format of attachment page urls from /[post-url]/[attachment-name]/ to /media/[attachment-name]/? I understand that I can override the output of get_attachment_link via the attachment_link filter, but I guess I need to change the redirect structure so WordPress knows how to handle these urls?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can do the following:
/* add new rewrite rule */
function attachment_rewrite( $wp_rewrite ) {
$rule = array(
'media/(.+)' => 'index.php?attachment=' . $wp_rewrite->preg_index(1)
);
$wp_rewrite->rules = $rule + $wp_rewrite->rules;
}
add_filter( 'generate_rewrite_rules', 'attachment_rewrite' );
/* redirect standard wordpress attachments urls to new format */
function redirect_old_attachment() {
global $wp;
if( !preg_match( '/^media/(.*)/', $wp->request ) && isset( $wp->query_vars['attachment'] ) ) {
wp_redirect( site_url( '/media/' . $wp->query_vars['attachment'] ) , 301 );
}
}
add_filter( 'template_redirect', 'redirect_old_attachment' );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0