Skip to content

Instantly share code, notes, and snippets.

Forked from retgef/pug-bomb.php
Created February 2, 2016 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlongren/c7340badd51e2a97954a to your computer and use it in GitHub Desktop.
Save tlongren/c7340badd51e2a97954a to your computer and use it in GitHub Desktop.
Pug Bomb API Endpoint WordPress Plugin
Plugin Name: Pug Bomb API Endpoint
Description: Adds an API endpoint at /api/pugs/$n_pugs
Version: 0.1
Author: Brian Fegter
Author URL:
class Pugs_API_Endpoint{
* @var string Pug Bomb Headquarters
protected $api = '';
/** Hook WordPress
* @return void
public function __construct(){
add_filter('query_vars', array($this, 'add_query_vars'), 0);
add_action('parse_request', array($this, 'sniff_requests'), 0);
add_action('init', array($this, 'add_endpoint'), 0);
/** Add public query vars
* @param array $vars List of current public query vars
* @return array $vars
public function add_query_vars($vars){
$vars[] = '__api';
$vars[] = 'pugs';
return $vars;
/** Add API Endpoint
* This is where the magic happens - brush up on your regex skillz
* @return void
public function add_endpoint(){
/** Sniff Requests
* This is where we hijack all API requests
* If $_GET['__api'] is set, we kill WP and serve up pug bomb awesomeness
* @return die if API request
public function sniff_requests(){
global $wp;
/** Handle Requests
* This is where we send off for an intense pug bomb package
* @return void
protected function handle_request(){
global $wp;
$pugs = $wp->query_vars['pugs'];
$this->send_response('Please tell us how many pugs to send.');
$pugs = file_get_contents($this->api.$pugs);
$this->send_response('200 OK', json_decode($pugs));
$this->send_response('Something went wrong with the pug bomb factory');
/** Response Handler
* This sends a JSON response to the browser
protected function send_response($msg, $pugs = ''){
$response['message'] = $msg;
$response['pugs'] = $pugs;
header('content-type: application/json; charset=utf-8');
echo json_encode($response)."\n";
new Pugs_API_Endpoint();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment