2016-02-09 160 views
0

您好我需要找到一種方法來重定向刪除的頁面到另一個頁面使用301重定向到一個特定的頁面取決於頁面的URL。如果URL是 http://example.com/projects/test-page-redirectpage/那麼它應該重定向到'redirectpage'在頁面刪除後。有數百頁像在URL末尾有'redirectpage'的頁面,所以我不能通過手動和重定向插件來做到這一點。我寫了下面的代碼,但它只能通過頁面名稱。我希望這樣可以檢測從URL中「redirectpage」,如果該URL不那麼退出它應該重定向到「redirectpage」已刪除頁面的重定向

function get_page_by_name($pagename) 
{ 
$pages = get_pages(); 
foreach ($pages as $page) if ($page->post_name == $pagename) return $page; 
return false; 
} 
function redirect_301() { 
$page = get_page_by_name('test-page-redirectpage'); 
if (empty($page)) { 
wp_safe_redirect(home_url('http://example.com/redirectpage/'), 301); 
exit; 
} 
} 
add_action('template_redirect', 'redirect_301', 1); 
+0

需要注意的是一個310重定向是不是刪除的頁面進行適當的處​​理。 [HTTP規範](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.11)爲不再可用的內容定義了「410 GONE」消息。有一個[WordPress插件](https://wordpress.org/plugins/wp-410/)爲刪除的內容執行該作業。它還允許您爲響應創建模板文件。 –

回答

0

您是使用正確的功能但是你應該檢查是否URL可以被翻譯後ID和當前請求的URL(全球$wp對象)redirectpage串的發生(在它的結束):

function so_423_redirectpage_redirect() 
{ 
    global $wp; 

    if (url_to_postid(home_url($wp->request)) === 0 && 
    ('redirectpage' === substr(untrailingslashit($wp->request), -12) || 'redirect-page' === substr(untrailingslashit($wp->request), -13))) { 
     wp_safe_redirect(home_url('http://example.com/redirectpage/'), 301); 
     exit(); 
    } 
} 
add_action('template_redirect', 'so_423_redirectpage_redirect'); 
+0

感謝您的回答,但我不想重定向所有頁面,最後有'redirectpage'字符串,我只想重定向那些已刪除或不存在的網址。 – Johny

+0

假設這個URL不存在http://example.com/projects/hello-redirectpage/,如果用戶轉到那個頁面,那麼用戶應該重定向到 http://example.com/redirectpage/ – Johny

+0

@Johny,我編輯了代碼,它使用'url_to_postid'來檢查頁面是否存在 –

0

我想你應該在這裏(從你的主題)使用404.php文件模板,所以你很確定訪問的頁面不存在。 的get_header()功能之前,你可以做以下檢查:

$requested_uri = explode('/', $_SERVER[REQUEST_URI]); 
if(strpos(array_pop($requested_uri), '-redirectpage') !== FALSE) { 
    wp_safe_redirect(site_url('redirectpage'), 301); 
} 
+0

我喜歡使用404的想法。也許它可以和我的答案結合起來,而不是用'url_to_postid()'檢查來使用'is_404() –