web-dev-qa-db-fra.com

Changer les URL d'attachement?

Comment modifier le format des URL de pages de pièces jointes de /[post-url]/[attachment-name]/ à /media/[attachment-name]/? Je comprends que je peux remplacer la sortie de get_attachment_link via le filtre attachment_link, mais je suppose que je dois modifier la structure de redirection afin que WordPress sache comment gérer ces URL?

6
Jan Fabry

Vous pouvez faire ce qui suit:

/* 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' );
7
sorich87