How to Link to External Links from the Post Title in WordPress

Watch out! This tutorial is over 8 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

Do you want to add an external link as post title in WordPress? Sometimes you may just want to share a link with your users. Instead of sending them to a post, you may want the post title to link to the other website. In this tutorial, we will show you how to link to external links from the post title in WordPress.

First, add this code to your theme’s functions.php file.

function print_post_title() {
global $post;
$thePostID = $post->ID;
$post_id = get_post($thePostID);
$title = $post_id->post_title;
$perm = get_permalink($post_id);
$post_keys = array(); $post_val = array();
$post_keys = get_post_custom_keys($thePostID);

if (!empty($post_keys)) {
foreach ($post_keys as $pkey) {
if ($pkey=='external_url') {
$post_val = get_post_custom_values($pkey);
}
}
if (empty($post_val)) {
$link = $perm;
} else {
$link = $post_val[0];
}
} else {
$link = $perm;
}
echo '<h2><a href="'.$link.'" rel="bookmark" title="'.$title.'">'.$title.'</a></h2>';
}

This code looks simply looks for a custom field containing your custom URL. If the post has the custom field, then it outputs the post title linked to your URL.
The next step is to replace your theme’s default display of post title with this function. You will find it in archives.php, content.php, category.php and other templates. It would look something like this:

<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>

You need to replace it with this code:

<?php print_post_title() ?>

The code part is over, now you need to add the external URL to the post. Simply edit the post or create a new one. On the post editor page, look for the “custom fields” meta box.

If you cannot see the custom fields meta box, then you need to click Screen Options in the top right corner of the screen. This will bring down a menu where you need to check the box next to ‘Custom Fields’.

You will find the custom fields meta box below the post editor.

Click on ‘Enter New’ and then enter external_url in the ‘Name’ field and the URL you want to add to post title in the ‘Value’ field.

You can now save or publish your post. That’s all, your post title will now be linked to the URL you added in the custom field.

Next time you need to add a link, you just need to select the external_url custom field from the drop down menu and enter your external link in the value field!

As with most things in WordPress, there is also a plugin that does the above… but you have to admit it is more fun doing it ourselves 🙂