Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // function.php
- function custom_api_get_document_callback($request){
- $posts_data = array();
- $key = $request->get_param('key');
- $id = $request->get_param('id');
- $posts = get_posts( array(
- 'post_type' => 'documents',
- 'status' => 'published',
- 'p' => $id
- ));
- foreach($posts as $post){
- $id = $post->ID;
- $pkey = get_field("password", $id);
- $file = get_field("documents_upload", $id);
- $filename = $file['filename'];
- if($pkey == $key){
- $posts_data[] = (object)array(
- 'message' => 'Success',
- 'file' => $file,
- 'name' => $filename
- );
- }else{
- $posts_data[] = (object)array(
- 'message' => 'Failed',
- 'file' => ''
- );
- }
- }
- return $posts_data;
- }
- //JS
- $('.verify-key').on('click',function(event){
- event.preventDefault();
- let $site = 'https:...';
- let $key = $('.docu-key').val();
- let $id = $(this).attr('data-id');
- $.getJSON($site+"wp-json/documents/document?page=1&id="+$id+"&key="+$key, function(data){
- if(data.length){
- let items = [];
- let $message, $file, $alert, $filename;
- $.each(data, function(key, val){
- const arr = $.map(val, function(el) { return el });
- $message = arr[0];
- $file = arr[1];
- $filename = arr[2];
- });
- if($message == "Success"){
- $alert = "Password correct";
- //$('.download-file-here').html('<a href="'+$file+'" download>Download Now</a>');
- fetch($file)
- .then(resp => resp.blob())
- .then(blob => {
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.style.display = 'none';
- a.href = url;
- // the filename you want
- a.download = $filename;
- document.body.appendChild(a);
- a.click();
- window.URL.revokeObjectURL(url);
- alert('Your file has downloaded!'); // or you know, something with better UX...
- })
- .catch(() => alert('Try again'));
- }else{
- $alert = "Password Incorrect";
- }
- $('.message-docu').html($alert);
- }
- });
- });
Add Comment
Please, Sign In to add comment