WordPress Snippets at WPcustoms

Use TinyURL with a shortcode

Easily add a tinyURL link with this shortcode snippet. Add it to your functions.php and use this shortcode in your posts: [tinyurl url=”http://google.com” title=”google”]


/**
 * Snippet Name: Use TinyURL with a shortcode
 * Snippet URL: http://www.wpcustoms.net/snippets/use-tinyurl-shortcode/
 */
 // usage: [tinyurl url="http://google.com" title="google"]
function wpc_shortcode_tinyurl($atts){
  extract(shortcode_atts(array(
   'url' => get_permalink(),
   'title' => '',
   'rel' => 'nofollow'
  ), $atts));
  if(!$title) $title = $url;

  if (FALSE === ($cache = get_transient('tinyurl_'+md5($url)))):
    $cache = wp_remote_retrieve_body(wp_remote_get('http://tinyurl.com/api-create.php?url='.$url));

    set_transient('tinyurl_'+md5($url), $cache, 60*60*24); // 1 day cache, could be incresed
  endif;

  return ''.esc_attr($title).'';
}
add_shortcode('tinyurl', 'wpc_shortcode_tinyurl');