December 16, 2016 · Web WordPress

Custom Wordpress restful api builder

Version v3.0x or above

themes/{yourtheme}/function.php

/**
 * HTTP JSON RESPONSE
 *
 * @param $ary
 * @param $status int 200|500|404
 */
function responseJSON($ary,$status){
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json;');

    switch ($status) {
        case 200:
            header($_SERVER['SERVER_PROTOCOL'].' 200 OK',true);
            wp_send_json($ary);
            break;
        case 500:
            header($_SERVER['SERVER_PROTOCOL'].' 500 Internal Server Error', true );
            break;
        default:
        case 404:
            header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true );
            break;
    }
}

/**
 * Handle RESTful API Call
 * 'http://www.example.com/restapi/?action=action&others1=a&others2=b
 *
 * Get More Posts Pagination
 *  @param string   $_GET ['action']  'action'
 *  @param int      $_GET ['others1']   'Your Parameters set'
 *  @param int      $_GET ['others2']   'Your Parameters set'
 *
 * @return JSON $ret json array
 */
function restfulAPIHandle()
{
    //Check if it is calling restful api
    $currentUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $regex = "/http:\/\/www\.example\.com\/restapi/";
    $isRESTful = preg_match($regex, $currentUrl);

    if (!$isRESTful) {
        return;
    }

    //Handling action
    $ret = [];
    $action = $_GET['action'];
    switch ($action) {
        case 'action':
            $ret =['1','2','3'];
            //Cast it into array
            $ret = json_decode(json_encode($ret), true);
            break;
        default:
            $ret = ['Action does not exists.'];
            break;
    }
    responseJSON($ret,200);
}

add_action('template_redirect', 'restfulAPIHandle');