After a long I get time to post because of very busy schedule.Today I arranged some time and come with something new. In this article, I am going to explain how you can use external URL in WordPress and redirect to that URL when clicking on post/link.
Recently, I was working on one theme and in that I am importing posts from other sites and want to redirect to actual /origin site if click on title or link found in google.
So, Let’s understand how I have done it. I have stored external URL/link as guid into the post in WordPress and permalink will be a URL of our site.So, we need to rewrite and redirect to URL and need to change the permalink.
Well, following filter hook is used to replace permalink with guid, if post’s guid is different than the site’s base URL. Here, I can get Host URL by parse_url function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function the_externalPermalink($url) { global $post; $parsed_arr = parse_url($post->guid); $parse_wphome = parse_url(get_bloginfo('url')); if($parsed_arr['host'] == $parse_wphome['host']){ return $url; }else{ $url = $post->guid; return $url; } } |
Next, action hook is used for redirecting template means if permalink of the own site found in somewhere or in the search engine, We also need to redirect to external/ original URL.Here, I have used the same condition like above just changes code of redirection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | add_action( 'template_redirect', 'isExternalURL' ); /** * return header message */ function isExternalURL() { global $wpdb,$post; if ( is_404() ) return; if(is_single()){ $guid = parse_url($post->guid); $url_host = $guid['host']; $blogin = get_bloginfo('home'); $home_url = parse_url($blogin); $home_host= $home_url['host']; if($home_host!=$url_host){ header( 'Location: ' . $post->guid ); }else{ return true; } } } |
That’s it. Place above code into your theme’s function.php file and run the code into browser :).
Recommended Read:
WordPress Action Hook
Auto-tagging in WordPress
To get Last auto increment id in WordPress
Hope this helps someone else out.As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.
Comments (1)