最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

permalinks - How do I make 301 redirection from `%post_id%` to `%postname%`?

programmeradmin4浏览0评论

My permalinks is set to /%post_id%/ (post id).

/%post_id%/

I want to change them all to /%postname%/ (which is the post slug).

/%postname%/

Problem is, whenever I change it, it gives 404 errors from my old page urls.

for example, this: /

should change to: /

But it gives 404 instead.

How do I make 301 redirection from /%post_id%/ to /%postname%/?

My permalinks is set to /%post_id%/ (post id).

https://elrons.co.il/%post_id%/

I want to change them all to /%postname%/ (which is the post slug).

https://elrons.co.il/%postname%/

Problem is, whenever I change it, it gives 404 errors from my old page urls.

for example, this: https://elrons.co.il/1779/

should change to: https://elrons.co.il/pil-kahol-font/

But it gives 404 instead.

How do I make 301 redirection from /%post_id%/ to /%postname%/?

Share Improve this question asked Aug 21, 2020 at 8:52 ElronElron 1595 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

I've written my own solution, sharing it and hoping it will help someone.

Add this to your 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;
            }

        }
    }
}

You can do it by .htaccess file, for your case url format as;

Redirect 301 /%post_id%/ https://elrons.co.il/%postname%/

Or

By redirection plugin, for example 301 Redirects – Easy Redirect Manager

发布评论

评论列表(0)

  1. 暂无评论