Changing attachment urls?

时间:2010-09-23 作者:Jan Fabry

如何更改附件页URL的格式/[post-url]/[attachment-name]//media/[attachment-name]/? 我知道我可以覆盖get_attachment_link 通过attachment_link 过滤器,但我想我需要更改重定向结构,以便WordPress知道如何处理这些URL?

1 个回复
最合适的回答,由SO网友:sorich87 整理而成

您可以执行以下操作:

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

结束

相关推荐