Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP redirection for slug rewrite/permalink

on my WordPress backend I have this php code for post type blog. Basically, I’m trying to change the rewrite slug from blogs/%category% to news-and-insights but I also need to redirect all the existing blog post to this new slug.

orginal code

I tried to edit the code as follow, the redirection is working but the page is not loading has the error "ERR_TOO_MANY_REDIRECTS"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(I also tried to redirect with regex Yoast plugin and Redirection plugin but still same error.)

modified slug rewrite

// Redirection from old slug to new slug
add_action('template_redirect', 'redirect_old_blog_urls');
function redirect_old_blog_urls()
{
    if (is_singular('blog')) {
        global $post;

        // Get the current URL
        $current_url = home_url(add_query_arg(array(), $wp->request));

        // Define the old URL pattern
        $old_url = home_url('blogs/' . get_the_category($post->ID)[0]->slug . '/' . $post->post_name);

        // Define the new URL pattern
        $new_url = home_url('news-and-insights/' . $post->post_name);

        // Check if the current URL matches the old URL pattern
        if (untrailingslashit($current_url) === untrailingslashit($old_url)) {
            wp_redirect($new_url, 301);
            exit;
        }
    }
}

>Solution :

Given that you want to change the slug for a specific custom post type without affecting other post types, you can achieve this by using WordPress’s rewrite rules specifically for your custom post type. Here’s how you can update the slug for your blog custom post type and handle redirections correctly:

Step 1: Update the Custom Post Type Registration

Update your register_post_type function to use the new slug news-and-insights:

function custom_post_type() {
    register_post_type('blog', array(
        'rewrite' => array('slug' => 'news-and-insights'),
        'has_archive' => true,
        'public' => true,
        'label' => 'Blogs',
        'supports' => array('title', 'editor', 'thumbnail'),
        // Other arguments here...
    ));
}
add_action('init', 'custom_post_type');

Step 2: Add a Redirection for Old URLs

Next, you need to set up a redirection from the old URLs to the new ones. Here’s a function to handle that:

// Redirection from old slug to new slug
add_action('template_redirect', 'redirect_old_blog_urls');
function redirect_old_blog_urls() {
    if (is_singular('blog')) {
        global $post;

        // Check if we're already handling a redirect to avoid an infinite loop
        if (get_query_var('redirected')) {
            return;
        }

        // Get the current URL
        $current_url = home_url(add_query_arg(array(), $wp->request));

        // Define the old URL pattern
        $old_url_pattern = home_url('blogs/' . get_the_category($post->ID)[0]->slug . '/' . $post->post_name);

        // Define the new URL pattern
        $new_url = home_url('news-and-insights/' . $post->post_name);

        // Check if the current URL matches the old URL pattern
        if (untrailingslashit($current_url) === untrailingslashit($old_url_pattern)) {
            // Add a query variable to mark that the redirect has happened
            $new_url = add_query_arg('redirected', '1', $new_url);
            wp_redirect($new_url, 301);
            exit;
        }
    }
}

// Add the query variable to the list of recognized query vars
function add_redirected_query_var($vars) {
    $vars[] = 'redirected';
    return $vars;
}
add_filter('query_vars', 'add_redirected_query_var');

Step 3: Flush Rewrite Rules

After making these changes, you need to flush the rewrite rules to apply the new rewrite slug. You can do this by visiting the WordPress Permalinks settings page (Settings > Permalinks) and simply clicking the "Save Changes" button.

Step 4: Ensure Proper Redirection Handling

To ensure the redirection doesn’t cause an infinite loop and that the new URLs are correctly served, the redirect_old_blog_urls function uses a query variable to track the redirection state. This prevents the redirection logic from being applied recursively.

By following these steps, you should be able to change the slug for your blog custom post type without affecting other post types on your WordPress site, and ensure that old URLs are properly redirected to the new URLs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading