-
-
Notifications
You must be signed in to change notification settings - Fork 14
Custom Shortener
Allen Fayland edited this page Jun 13, 2021
·
4 revisions
Adding your own custom shortener takes just two steps. First, create a shorten class for accessing your API of choice. Next, add a filter to activate it.
The file for your shortener class can live anywhere in your WordPress site codebase. It must implement the Shorten interface provided at /wp-content/plugins/utm-dot-codes/classes/shorten/interface.php
and contain the methods:
- shorten()
- get_response()
- get_error()
<?php
/**
* Sample API shortener class.
*
* @package UtmDotCodes
*/
namespace UtmDotCodes;
/**
* Class Sample.
*/
class Sample implements \UtmDotCodes\Shorten {
const API_URL = 'https://api.service.tld/v1';
/**
* API credentials for sample API.
*
* @var string|null The API key for the shortener.
*/
private $api_key;
/**
* Response from API.
*
* @var object|null The response object from the shortener.
*/
private $response;
/**
* Error message.
*
* @var object|null Error object with code and message properties.
*/
private $error_code;
/**
* Sample constructor.
*
* @param string $api_key Credentials for API.
*/
public function __construct( $api_key ) {
$this->api_key = $api_key;
}
/**
* See interface for docblock.
*
* @inheritDoc
*
* @param array $data See interface.
* @param string $query_string See interface.
*
* @return void
*/
public function shorten( $data, $query_string ) {
// Logic to submit request to API and set response/error from response.
}
/**
* Get response from Sample API for the request.
*
* @inheritDoc
*/
public function get_response() {
return $this->response;
}
/**
* Get error code/message returned by Sample API for the request.
*
* @inheritDoc
*/
public function get_error() {
return $this->error_code;
}
}
The utmdc_shorten_object
filter allows you to replace the active shortener with your own custom shorten object. To enable your shortener include the shorten class file and return an instance of it's shorten object.
add_filter('utmdc_shorten_object', function( $shortener ){
include_once 'PATH_TO_YOUR_/shortener.php';
return new CustomShortener( 'YOUR_API_KEY' );
});
utm.codes is proudly open source software.