Nicola D'Agostino (.net) - Articoli, traduzioni, grafica, web

How to link the title of a WordPress posts to an external url

Note to myself: when upgrading your WordPress installation remember to add back this function, and when you change the theme change the code instances, too.

Wouldn’t it be nice if you could link the title of a WordPress posts to an external url on an occasional basis in a few moments?

wordpress custom field external url

Cool, huh? This is how you do it!

First of all this piece of code goes into your /wp-includes/functions.php file (add it back when you do big WordPress upgrades!)

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 '<a href="'.$link.'">'.get_the_title().'</a>';
}

You also have to change all of the the instances of

<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?>

in your theme’s index.php file with this code

<span class="storytitle" id="post-<?php the_ID(); ?>"><strong><?php agentwp_print_post_title(); ?></strong></span>

In some themes, like the one I’m using (Grey and Simple), there are multiple instances of the code to modify.
In my theme they are five, at lines 39, 75, 98, 119 and 140 and the code is the same, i.e.:


<span class="storytitle" id="post-<?php the_ID(); ?>"><strong><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></strong></span>

Finally, in each post in which you wish the url to point elsewhere add a new custom field with the following two things

Name: external_url
Value: http://www.yoururl.xyz