将 Wordpress Media 附件页面重定向到根位置

Redirect Wordpress Media attachment page to root location

我以前的网站结构是 example.com/wp。我已经搬到example.com

所以现在我正在尝试使用 wp_redirect 重定向 301 我所有的媒体附件页面(超过 1500 页),如下所示:

example.com/wp/image1  ====> example.com/image1

我正在使用这个钩子

add_action( 'template_redirect', 'wpsites_attachment_redirect' );
function wpsites_attachment_redirect(){
global $post;
if ( is_attachment() && isset($post->post_parent) && is_numeric($post->post_parent) && ($post->post_parent != 0) ) :
    wp_redirect( get_permalink( $post->post_parent ), 301 );
    exit();
    wp_reset_postdata();
    endif;
}

想法是 wp_redirect( example.com/>Any attachment link here<, 301 );

创建文件image.php

将代码粘贴到文件中并将其上传到您的主题根目录。

<?php wp_redirect( get_permalink( $post->post_parent ), 301 ); exit; ?>

这比我想象的要容易,这里是解决方案:

add_action( 'template_redirect', 'wpsites_attachment_redirect' );
function wpsites_attachment_redirect(){
global $post;
if ( is_attachment() && isset($post->post_parent) && is_numeric($post->post_parent) && ($post->post_parent != 0) ) :

    $actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $actual_link = $actual_link.'/'.$post->post_parent;
    $actual_link = str_replace('/wp/','/',$actual_link);
    wp_redirect( $actual_link, 301 );
    exit();
    wp_reset_postdata();
    endif;
}

替代文件 image.php 与没有 post-parent 的媒体附件页面兼容! (这是与其他两个答案的混合)

<?php if ( is_attachment() && isset($post->post_parent) && is_numeric($post->post_parent) && ($post->post_parent != 0) ) :

wp_redirect( get_permalink( $post->post_parent ), 301 ); exit;

endif; ?>

<?php wp_redirect( get_bloginfo('wpurl'), 301 ); exit; ?>