Skip to content

Instantly share code, notes, and snippets.

@theblanchard
Created October 17, 2016 03:42
Show Gist options
  • Save theblanchard/920dc2ebcddf94f7ac43bad1f4c6c6f3 to your computer and use it in GitHub Desktop.
Save theblanchard/920dc2ebcddf94f7ac43bad1f4c6c6f3 to your computer and use it in GitHub Desktop.
Get permalinks from the bit.ly API
$title = str_replace(' ', '', get_the_title());
$title = str_replace('-', '', $title);
$permalink = get_the_permalink();
// Set the path to save the data to
$cachePath = ABSPATH.'path/to/folder/'.$title.'.txt';
// See if data already exists
$getData = file_get_contents($cachePath);
$response = json_decode($getData, true);
// Search the array
$key = array_search($permalink, $response);
if (!empty($key)) {
// Found data, use the existing shortlink
$keyData='shortlink';
$shortlink = $response[$keyData];
} else {
// Found no data, generate new shortlink
// Include the bit.ly API files
include_once('json.php');
include_once('bitly.php');
// Set up the parameters
$results = new json(); $results->status_code = 501;
$token = 'e326cf213c40a7b21a2aa93eca0b967e22c228f1';
$domain = 'mklnd.com';
$link = get_the_permalink();
$shortUrl = bitly_v3_shorten($link, $token, $domain);
if($link) $results = bitly_v3_shorten($link, $token, $domain);
$shortlink = $results['url'];
// Create array from new data
$urlArray = array (
'permalink' => get_the_permalink(),
'shortlink' => $shortlink
);
// Save the new data to the cache file
file_put_contents($cachePath,json_encode($urlArray));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment