Last active
April 26, 2020 15:42
-
-
Save krasenslavov/339643014415a5b46a8d561bf67db714 to your computer and use it in GitHub Desktop.
Use Bitly to generate short URLs in WordPress. Visit blog post https://bit.ly/2XB3M8s
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action('publish_post', function ($post_id) { | |
global $wpdb; | |
$api_key = 'GENERATED_ACCESS_TOKEN'; | |
$api_url = 'https://api-ssl.bitly.com/v4/bitlinks'; | |
$data = array( | |
'long_url' => get_permalink($post_id) | |
); | |
$payload = json_encode($data); | |
$header = array( | |
'Authorization: Bearer ' . $api_key, | |
'Content-Type: application/json', | |
'Content-Length: ' . strlen($payload) | |
); | |
$curl = curl_init($api_url); | |
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); | |
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); | |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); | |
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); | |
$result = curl_exec($curl); | |
$resultJSON = json_decode($result); | |
if (isset($resultJSON->link)) { | |
update_post_meta($post_id, 'bitly_url', $resultJSON->link); | |
} | |
}, 10, 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment