How To Link WordPress Post Title To An External URL

You must have come across this situation when you had to create a new post just to share a link with your readers. Its not annoying just to you, but for your readers as well, as they have to click the post title to get the link from post body. One elegant solution to this issue is to use the following hack to directly link the post title to an external URL.

First, open the functions.php file in your theme folder and paste the following code in it,

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=='url1' || $pkey=='title_url' || $pkey=='url_title') {
$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>';
}

Then open your index.php file (or home.php file if your theme uses that), and find the standard code for printing post titles,

<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2>

Now, replace this with,

<?php print_post_title() ?>

Your theme is now ready to use external links as post titles. To create a post whose title links to an external resource, go to write post panel and enter the post title as usual. Then scroll down a bit to find the custom fields box. Create a custom key with name url1, title_url, or url_title and in the value field, add the link to external resource.

link post title to external url How To Link WordPress Post Title To An External URL

Don’t add anything in post’s body and publish the post. The title for this post will now link to the url you entered in the value part of the custom field.

Also, don’t worry about this customization while creating normal posts. It doesn’t affect normal posts. This hack comes into play only for the posts with the custom field with name url1, title_url, or url_title.

share on twitter

Comments

  1. David says:

    I would like to style the external links differently to the standard page title links. I suspect it has something to do with creating a CSS class for $pkey in the funtions.php file, but I’m not clear about how to do that. I’d appreciate it if you could help.

  2. Mayur Somani says:

    @David

    In the last line of print_post_title function, add a custom class and then add styles for it in the style.css file.

Leave a Reply