【问题标题】:Wordpress : Redirect Wordpress attachment URLWordpress : 重定向 Wordpress 附件 URL
【发布时间】:2015-12-15 16:25:24
【问题描述】:

是否有人可以为我重定向以下永久链接 URL?

WordPress的网址是:http://example.com/?attachment_id=411

我想将它重定向到我这样做的新结构,以下代码在旧 URL 中不适用于我:-

/* 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 );
        exit();
    }
}
add_filter( 'template_redirect', 'redirect_old_attachment' );
/**/
function wpd_attachment_link( $link, $post_id ){
    $post = get_post( $post_id );
    return home_url( '/media/' . $post->post_name );
}
add_filter( 'attachment_link', 'wpd_attachment_link', 20, 2 );

所以我们需要在打开http://example.com/?attachment_id=411时,重定向到http://example.com/media/post-title

【问题讨论】:

  • 详细阐述您的问题,例如输入和输出结构。
  • 我需要打开http://example.com/?attachment_id=411,重定向到http://example.com/media/post-title

标签: php wordpress redirect


【解决方案1】:

将您现有的代码更新为以下代码,

//Modify attachment page link
add_filter( 'attachment_link', 'wp_attachment_link', 20, 2 );
function wp_attachment_link( $link, $attachment_id ){
    $attachment = get_post( $attachment_id );
    $attachment_title = $attachment->post_title ;
    $attachment_title = str_replace( ' ' , '-' , $attachment_title );
    $site_url = get_site_url( $attachment_id );
    $link =  $site_url . '/media/'  .$attachment_title;
    return $link;
}
// Rewrite attachment page link
add_action( 'init', function() {
    add_rewrite_rule( 'media/([A-Za-z0-9-]+)?$', 'index.php?attachment_id=$matches[2]', 'top' );

} );

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2011-05-30
    • 2017-06-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多