Created
May 10, 2016 01:07
-
-
Save DArcMattr/ea273867a313d636b4369263815fe47c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Minimal Rest API | |
Description: Very minimal DIY REST API plugin scaffold, must refresh permalink | |
settings to get this to work | |
*/ | |
/** | |
* WP Init Action hook function | |
* | |
* @param null | |
* | |
* @return null | |
*/ | |
function minimal_rest_init() { | |
global $wp; | |
$wp->add_query_var( 'api' ); | |
} | |
add_action( 'init', 'minimal_rest_init' ); | |
/** | |
* Activation Hook function | |
* | |
* @param null | |
* | |
* @return null | |
*/ | |
function minimal_rest_activate() { | |
add_rewrite_rule( '^api/?$', 'index.php?api=/', 'top' ); | |
add_rewrite_rule( '^api(.*)?', 'index.php?api=$matches[1]', 'top' ); | |
flush_rewrite_rules(); | |
} | |
register_activation_hook( __FILE__, 'minimal_rest_activate' ); | |
/** | |
* Given a request going to {site_url}/api/{endpoint}, echo the response array in | |
* JSON form | |
* | |
* @param null | |
* | |
* @return null | |
*/ | |
function minimal_rest_process_callback() { | |
if ( empty( $GLOBALS['wp']->query_vars['api'] ) ) { | |
return; | |
} | |
switch ( $GLOBALS['wp']->query_vars['api'] ) { | |
case '/endpoint': | |
$content = array('hello' => 'world'); | |
break; | |
default: | |
$content = array(); | |
} | |
wp_send_json( $content ); | |
die(); | |
} | |
add_action( 'template_redirect', 'minimal_rest_process_callback', PHP_INT_MIN ); | |
/** | |
* Logic for relaying REST input | |
* | |
* Hardly any input validation here. Do not use as-is! | |
* | |
* @param null | |
* | |
* @return array | |
*/ | |
function minimal_rest_populate_data() { | |
switch ( $_SERVER['REQUEST_METHOD'] ) { | |
case 'POST': | |
$return = (array) json_decode( file_get_contents( 'php://input' ), true ); | |
$return['REQUEST_METHOD'] = 'POST'; | |
case 'GET': | |
case 'PUT': | |
case 'DELETE': | |
foreach ( $_REQUEST as $key => $value ) { | |
$return[$key] = trim( $value ); | |
} | |
$return['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD']; | |
break; | |
default: | |
} | |
return $return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment