attachment url rewrite

Actually, you can always just use a query parameter, even if you have the “pretty” permalinks enabled. So instead of /category/sub-category/article.html/attachment/image you can go to /?attachment=image. The only case when this “breaks down” is when you go to /category/sub-category/article.html?attachment=image, because WordPress gets confused: it tries to query for a post and an attachment at the same time. However, this is very simple to handle: check for the request, and if it is an attachment remove the other parameters.

add_action( 'parse_request', 'wpse5015_parse_request' );
function wpse5015_parse_request( $wp )
{
    if ( array_key_exists( 'attachment', $wp->query_vars ) ) {
        unset( $wp->query_vars['name'] );
        unset( $wp->query_vars['year'] );
        unset( $wp->query_vars['monthnum'] );
    }
}

Now you only have to change the generated attachment URLs. Since they are almost in the correct format, we can just so some search and replace:

add_filter( 'attachment_link', 'wpse5015_attachment_link', 10, 2 );
function wpse5015_attachment_link( $link, $id )
{
    // If the attachment name is numeric, this is added to avoid page number conflicts
    $link = str_replace( 'attachment/', '', $link );
    $attachment = get_post( $id );
    $link = str_replace( "https://wordpress.stackexchange.com/" . $attachment->post_name . "https://wordpress.stackexchange.com/", '?attachment=" . $attachment->post_name, $link );
    return $link;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)