Link WordPress Post Title To An External URL

Sometimes you may need to link WordPress post title directly to an external URL. For example, if you want to share a link with your readers, what will you do? Its highly likely that you will create a post and add a link in it. Readers can then open the post on your web site and then click on the link. Wouldn’t it be better if the post title directly linked to the external URL?

You can easily link a post title on your WordPress site to an external URL. First, add this code to the functions.php file of your WordPress theme,

function agentwp_print_post_title() {
$external_url = get_post_meta(get_the_ID(), 'external_url', true);
if (empty($external_url)) {
$link = get_permalink();
} else {
$link = $external_url;
}
echo '<h2><a href="'.$link.'">'.get_the_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 code with the following code,

<?php agentwp_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 page, go to post edit screen and enter the post title as usual. Then scroll down a bit to find the custom fields box. Create a custom field with name external_url and in the value field, add the external link.

link post title to 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.

WordPress Plugin to Link Post and Page Titles To External URL

If you don’t want to play with the code to implement the functionality to link post titles to external url in WordPress, you can use this great plugin called Page Links To. This plugin adds a custom meta box to each of your WordPress posts and pages which lets you link it to any external URL.

page links to

In both the methods to link post titles to external URL, make sure to have http:// before the url, other wise the link will not work. If you want to add a placeholder or dummy link that actually doesn’t links to anything, you can use # for the link.

Comments

  1. David:

    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:

    @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.

Comment?

Your email address will not be published. Required fields are marked *