Improvement: Shorten any link
-
I did a small modification to the plugin i order to be able to shorten any link. Specifically, I need to shorten my permalink with appended UTM tracking parameters. So I split the wpbitly_generate_shortlink() function like this and can now call wpbitly_shorten_url() with my desired URL anywhere from my theme. I think it should be included in a future release!
/** * Generates the shortlink for the post specified by $post_id. * * @since 0.1 * * @param int $post_id The post ID we need a shortlink for. * * @return bool|string Returns the shortlink on success. */ function wpbitly_generate_shortlink($post_id) { $wpbitly = wpbitly(); // Avoid creating shortlinks during an autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return; // or for revisions if (wp_is_post_revision($post_id)) return; // Verify this is a post we want to generate short links for if (!in_array(get_post_type($post_id), $wpbitly->get_option('post_types')) || !in_array(get_post_status($post_id), array('publish', 'future', 'private'))) return; // We made it this far? Let's get a shortlink $permalink = get_permalink($post_id); $shortlink = get_post_meta($post_id, '_wpbitly', true); $token = $wpbitly->get_option('oauth_token'); if (!empty($shortlink)) { $url = sprintf(wpbitly_api('expand'), $token, $shortlink); $response = wpbitly_get($url); wpbitly_debug_log($response, '/expand/'); if ($permalink == $response['data']['expand'][0]['long_url']) return $shortlink; } $shortlink = wpbitly_shorten_url($permalink); if(!empty($shortlink)) { update_post_meta($post_id, '_wpbitly', $shortlink); } return $shortlink; } /** * Generates the shortlink for the url specified by $link * * @since 0.1 * * @param string $link The long link we need a shortlink for. * * @return bool|string Returns the shortlink on success or false. */ function wpbitly_shorten_url($link) { $wpbitly = wpbitly(); // Token hasn't been verified, bail if (!$wpbitly->get_option('authorized')) return false; $shortlink = false; $token = $wpbitly->get_option('oauth_token'); $url = sprintf(wpbitly_api('shorten'), $token, urlencode($link)); $response = wpbitly_get($url); wpbitly_debug_log($response, '/shorten/'); if (is_array($response)) { $shortlink = $response['data']['url']; } return $shortlink; }
- The topic ‘Improvement: Shorten any link’ is closed to new replies.