`/%post_id%/`から `/%postname%/`への301リダイレクトを行うにはどうすればよいですか?
Aug 21 2020
私のパーマリンクは/%post_id%/
(投稿ID)に設定されています。
https://elrons.co.il/%post_id%/
それらすべてを/%postname%/
(ポストスラッグ)に変更したいと思います。
https://elrons.co.il/%postname%/
問題は、変更するたびに、古いページのURLから404エラーが発生することです。
たとえば、これ: https://elrons.co.il/1779/
次のように変更する必要があります。 https://elrons.co.il/pil-kahol-font/
しかし、代わりに404を返します。
301をから/%post_id%/
にリダイレクトするにはどうすればよい/%postname%/
ですか?
回答
Elron Aug 21 2020 at 16:42
私は自分の解決策を書き、それを共有し、それが誰かを助けることを望んでいます。
これをあなたに追加してくださいfunctions.php
:
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}