2017-09-05 107 views
0

我的旧网站结构曾经是example.com/wp。我已经搬到example.com重定向Wordpress媒体附件页面到根位置

所以现在我正在试图用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);

回答

0

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

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; 
} 
0

创建一个文件image.php

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

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

问题是我有超过1500个附件重定向,这将带我永远。一个钩子会很好。 –

+0

Mrjack @hope这会帮助你 –

0

一个替代文件image.php与媒体附件页面不兼容父的帖子! (这是一个与其他两个答案混合)

<?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; ?>