Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 6 down vote accepted

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' );
share|improve this answer
    
where do we add the above code, do we add it in functions.php or rewrite.php or links-template.php –  Terrell Anderson Feb 27 '12 at 5:16
    
add it to your theme functions.php file –  sorich87 Feb 28 '12 at 12:38

protected by toscho Oct 1 '12 at 13:19

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.