Using WordPress ‘old_slug_redirect_post_id’ PHP filter

The old_slug_redirect_post_id WordPress PHP filter allows you to modify the redirect post ID when an old slug is detected.


add_filter('old_slug_redirect_post_id', 'your_custom_function', 10, 1);

function your_custom_function($id) {
    // Your custom code here
    return $id;


  • $id (int) – The redirect post ID.

More information

See WordPress Developer Resources: old_slug_redirect_post_id


Change redirect post ID

Update the redirect post ID based on your custom logic.

function update_redirect_post_id($id) {
    // Update the redirect post ID
    $new_id = 123;
    return $new_id;
add_filter('old_slug_redirect_post_id', 'update_redirect_post_id', 10, 1);

Cancel the redirect

Prevent the redirection by returning 0 as the redirect post ID.

function cancel_old_slug_redirect($id) {
    // Cancel the redirect
    return 0;
add_filter('old_slug_redirect_post_id', 'cancel_old_slug_redirect', 10, 1);

Redirect to a custom post type

Redirect to a custom post type with the same slug if the post ID is not found.

function custom_post_type_redirect($id) {
    if (!$id) {
        $slug = get_query_var('name');
        $custom_post = get_page_by_path($slug, OBJECT, 'custom_post_type');
        if ($custom_post) {
            return $custom_post->ID;
    return $id;
add_filter('old_slug_redirect_post_id', 'custom_post_type_redirect', 10, 1);

Log old slug redirects

Log the old slug redirects to a custom log file for further analysis.

function log_old_slug_redirects($id) {
    // Log the old slug redirects
    $log_message = "Old Slug Redirect: Post ID: {$id}\n";
    error_log($log_message, 3, '/path/to/your/custom/logfile.log');
    return $id;
add_filter('old_slug_redirect_post_id', 'log_old_slug_redirects', 10, 1);

Modify the redirect post ID based on user role

Change the redirect post ID based on the user role, redirecting users with different roles to different posts.

function user_role_based_redirect($id) {
    // Get the current user
    $current_user = wp_get_current_user();

    if (in_array('administrator', $current_user->roles)) {
        // Redirect administrators to a specific post
        $id = 456;
    } elseif (in_array('editor', $current_user->roles)) {
        // Redirect editors to a different post
        $id = 789;

    return $id;
add_filter('old_slug_redirect_post_id', 'user_role_based_redirect', 10, 1);