Have you changed your page or post name and slug for better SEO? Do You want to redirect the old URL to the new URL without using the plugin? In this article, we show you how to redirect an old URL to a new URL without using the plugin.
There are plugins available for handling this task. But we would suggest, always try to keep fewer plugins for your site. Doing the coding wherever possible is a better way rather than using a plugin every time. Keeping fewer plugins on the site is always a good practice. In most cases, you can achieve your target without a plugin also. You just need to write some piece code for it.
Redirecting the old URLs to the new location is also a task that can be done by using a few lines of code.
Redirect Old URL To New URL Without Plugin
Place the below code in your themes functions.php
and replaces the slug wherever necessary to fit your requirement.
add_action('wp_print_styles', 'redirect_old_url_to_new_url');
function redirect_old_url_to_new_url() {
global $post;
if ('old-url-slug' == $post->post_name) {
wp_redirect( site_url() . '/new-url-slug', 301 );
die();
}
}
That’s it! We hope you understand how to redirect the old URL to a new URL. If have any questions or suggestions please leave a comment below.
Related Articles
- How to Add Custom Endpoints to WordPress API
- How to Set a Fallback Image for WordPress Post Thumbnails
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
Hi dear
I want to redirect 301 to the below URL
worpress.com/NewsInfoPrint?id=13624
to
wordpress.com/news/13624/
// number is ID post in WordPress and I need for all posts to do that, so the number is dynamic
how can I do that?
Thank you vary much
Thank you! … helpful article
thank you very nice website article
how about redirect url with date not with date?