my posts have urls of two different types: one with post id and other with post slug:


i'm doing this using:


and setting up permalinks using %post_name%.

both /post/123 and /post/my-post-slug open the same html page.

is it possible to make wordpress return the 301 redirect to /post/my-post-slug when accessing /post/123?


yes, it is possible. add a template_redirect hook handler:

add_filter('template_redirect', 'redirect_post_to_canonical_url');

function redirect_post_to_canonical_url(): void
    if (!is_single()) {
        // do not redirect nothing else except posts

    $canonicalLocation = get_permalink();
    $requestUri = $_SERVER['REQUEST_URI'];
    $currentLocation = home_url('/') . substr($requestUri, 1);
    if ($currentLocation === $canonicalLocation) {
        // prevent from infinite redirect loop

    wp_redirect($canonicalLocation, 301);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.