我已经写了自己的解决方案,与大家分享,希望它能帮助别人。
将此添加到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;
}
}
}
}