`/ % 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를 제공합니다.

에서에서 /%post_id%/로 301 리디렉션 하려면 어떻게해야 /%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;
            }

        }
    }
}