I am trying to write a simple plugin that fetches some data from an API endpoint. I am planning to read the api key from a shortcode, but didn't get that far yet.

I wrote the following piece of code. The noob question I have is how do I even trigger the code so that I could debug it to see what happens ?

If that's a simple question, the follow up would be how to read the api key from a shortcode?


private static $instance;

 * Initializes the plugin and read some data
 * @access private
private function __construct()
    add_action('data', [$this, 'fetchData']);

 * Creates an instance of this class
 * @access public
 * @return DATA_PARSING    An instance of this class
public function get_instance()
    if (null == self::$instance) {
        self::$instance = new self;

    return self::$instance;

private function fetchData($apiKey)
    $url = 'https://api.website.com/data';
    $args = [
        'id' => 1234,
        'fields' => '*'
    $method = 'GET';
    $headers = array(
        'Authorization' => 'Bearer ' . $apiKey,
        'Accept' => 'application/vnd.website.v1+json',
        'content-type' => 'application/json',
    $request = array(
        'headers' => $headers,
        'method' => $method,

    if ($method == 'GET' && !empty($args) && is_array($args)) {
        $url = add_query_arg($args, $url);
    } else {
        $request['body'] = json_encode($args);

    $response = wp_remote_request($url, $request);

    try {
        $json = json_decode($response['body']);
    } catch (Exception $e) {
        $json = null;

    return $json;


you can call the function by putting this code in a template.

echo fetchData('YOUR_API_HERE');

you should change your first line from:

if you're looking to turn it into a shortcode add this line:

add_shortcode( 'fetch-short', 'fetchData'); 

either right above or below your function.

then change your function start to this:

function fetchData( $atts ) {
    $api = {$atts['api']}";  //this is your new api variable

your shortcode would be

[fetch-short api="YOUR_API"]

be careful to add checks for incase you someone doesn't add an api though. as in set a default or error check if $api is empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.