How to Redirect a Page/Post to External Site

external-linkUsually when you publish a new post, the post will be pushed to the top of the list in the front page. When your reader click the title link, it will bring them to the full article. Now, what if you want the title of the post, when clicked, direct the reader to an external URL instead of the full article? How can you do it without utilizing a plugin?

We can use custom field to solve this. Here is how you can do so:

Create a new post/page with excerpt/teaser that you want to show your reader. At the custom field section, create a new custom field “external_link” and place the external URL in the value field.

Now open up your index.php file. At the part that display the post title, it should look something like this:

<h2 class="entry-title"><a href="<?php the_permalink() ?>" title="Permalink to <?php the_title(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>

Replace it with the following code:

<?php 
	if(($external_link = get_post_meta($post->ID, 'external_link', true)))
		$title_link = $external_link;
	else
		$title_link = get_permalink();
?>
<a href="<?php echo $title_link; ?>" title="Permalink to <?php the_title(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>

What the above code does is to check if there is any external link set for the current post. If yes, it will replace the title link with the external link. When your reader click on the link, he/she will be directed to the external URL.

You can use the above code in archive pages such as category.php, tag.php, author.php or archives.php.

To insert the post with external link in your feed, open the functions.php file and paste the following code:

function wpdailybits_linkrss($content) {
    global $wp_query;
    $postid = $wp_query->post->ID;
    $external_link = get_post_meta($postid, 'external_link', true);
    if($external_link != '') {
		$content = $external_link;
    }
    return $content;
}
add_filter('the_permalink_rss', 'wpdailybits_linkrss');

That’s it. The post should appear in your RSS feed with an external clickthrough link.

Image credit: chrisdlugosz

Comments are closed.