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. 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" (I also tried to redirect with regex Yoast plugin and Redirection plugin but still same error.) // 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; } } }

Comment (1)

Jese Leos

August 10, 2024

Verified user

It could be an issue with how you're determining $current_url. Try getting the current page URL in PHP using the the PHP Superglobal variables instead as described here: $current_url="https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

You’ll be in good company