How to: Link to some external ressource in post title

January 16, 2009 at 8:12 am

Sometimes, you may want to publish a post which only consist of an url pointing to some external resource. As there’s no built-in function to do that in WordPress, let’s create our own!

The first thing to do is to open your functions.php file and paste the following code:

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>';
}

Once done, open your index.php file and replace the standard code for printing titles:

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

by a call to our newly created print_post_title() function:

<?php print_post_title() ?>

Now, whenever you feel like let your post title leave your blog and point someplace else, just scroll down in your post writing screen, create or select a custom key named url1 or title_url or url_title and put that external URL in value box.

Thanks to Vlad Grubman for this awesome recipe!