Storing links against wordpress posts. Posted on: 2012-05-18

When it comes to creating websites these days, one can't avoid including social media links for sharing. Twitter's good old 140 character limit on tweets has caused issues when it comes to using really long urls for me, so I've come to using the following:

/* Get the link for a url. If the link has already been created, get it from the post meta instead of making a curl request for every page load. */
function bitly($_link) {
    global $post;
    if (empty($_link)) $_link = get_permalink($post->ID);
    $_existing = get_post_meta($post->ID, 'bitly', true);
    if ($_existing !== false && !empty($_existing)) return $_existing;
    $_link = curl_get_result(''.urlencode($_link).'&format=txt');
    update_post_meta($post->ID, 'bitly', $_link);
    return $_link;

/* returns a result from url */
function curl_get_result($url) {
    $ch = curl_init();
    $timeout = 5;
    $data = curl_exec($ch);
    return $data;

This creates a link for the current post or for the link you pass in (if it doesn't exist already) and stores it in a post meta field for the post (so that we don't bombard on every page load). If you chuck this in your functions.php file, using it is as simple as follows:

<a title="some link description here" href=<?php echo bitly(); ?>">some link description here</a>