Skip to content

Instantly share code, notes, and snippets.

@sudipto-me
Created September 14, 2018 07:01
Show Gist options
  • Save sudipto-me/ac0388809d10a69df6caa0cb06893525 to your computer and use it in GitHub Desktop.
Save sudipto-me/ac0388809d10a69df6caa0cb06893525 to your computer and use it in GitHub Desktop.
This is my first working with wordpress rest api. Here I get a token in the header and a user-id from the url. By checking them I make a response which show the audio list from the uploads folder.
add_action('rest_api_init',function(){
register_rest_route('uploads','/audios/',array(
'methods'=>'GET',
'callback'=>'meditation_upload_file_auth',
));
});
function meditation_upload_file_auth(WP_REST_Request $request) {
$user_id = isset($_GET['userid'])?(int)$_GET['userid']:'';
$user_data = get_user_by('ID',$user_id);
$token = $request->get_header('token');
// $token = $attribues['args']['token'][0];
if(empty($token)) {
return new WP_Error( 'empty_token', 'Empty Token', array( 'status' => 404 ) );
}
if($token !='meditationpeggyapp'){
return new WP_Error( 'invalid_token', 'Invalid Token', array( 'status' => 404 ) );
}
if(empty($user_id)) {
return new WP_Error( 'empty_userID', 'Empty Userid', array( 'status' => 404 ) );
}
if($user_data ==false) {
return new WP_Error( 'invalid_userID', 'Invalid Userid', array( 'status' => 404 ) );
}else {
$upload_dir = wp_upload_dir();
if($dir=opendir($upload_dir['basedir'].'/audios')) {
$modules = array();
while(false!==($file=readdir($dir))) {
if($file!="." && $file!='..') {
$modules[] = $file;
}
}
closedir($dir);
sort($modules);
$response = array();
foreach($modules as $module) {
$count = 0;
$purchased_products = array();
$purchased_products['module_title'] = $module;
$listed_audios = glob($upload_dir['basedir'].'/audios/'.$module.'/*');
$count = 1;
foreach($listed_audios as $single_audio){
$purchased_products['products'][] = array(
'title'=>'audio '.$count,
'url'=> str_replace("/home/admin/web/meditationwithpeggygaines.com/public_html/wp-content/",$upload_dir['baseurl'].'/',$single_audio),
);
$count++;
}
$response[] = $purchased_products;
}
$json = array();
$json['success'] = true;
$json['message'] = 'Product fetch successful';
$json['purchased_products'] = $response;
$message = new WP_REST_Response($json, 200); // data => array of returned data
return $message;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment