sali1101
5/5/2020 - 12:16 AM

JQuery + API + Nonce

# https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

#1 - Get nonce in headers add to function.php 

function learningWordPress_resources() {
	
	wp_enqueue_style('style', get_stylesheet_uri());
	wp_enqueue_script('main_js', get_template_directory_uri() . '/js/main.js?ver=2', NULL, 1.0, true);
/* OLD from other tut 
	wp_localize_script('main_js', 'magicalData', array(
		'nonce' => wp_create_nonce('wp_rest'),
		'siteURL' => get_site_url()
	));
	*/
	
	wp_localize_script( 'main_js', 'wpApiSettings', array(
    'root' => esc_url_raw( rest_url() ),
    'nonce' => wp_create_nonce( 'wp_rest' )
) );
}

add_action('wp_enqueue_scripts', 'learningWordPress_resources');

# 2 - Shodecode ---
	
function my_form_shortcodee() {	

echo '

 <script src="https://code.jquery.com/jquery-3.1.1.min.js"
			  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
			  crossorigin="anonymous"></script>



<div class="admin-quick-add">
  <h3>Quick Add Post</h3>
  <input type="text" name="title" placeholder="Title">
  <textarea name="content" placeholder="Content"></textarea>
  <button id="quick-add-button">Create Post</button>
</div>' ;
	
echo '
<script>
$(document).ready(function(){

$.post("http://zenployee.tk/wp-json/wp/v2/posts?_wpnonce=" + wpApiSettings.nonce ,
  {
    title: "Donald Duckkota",
    
  },
  function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
  });
</script>

';	
	
	
		 		
} 
add_shortcode( 'motibilli', 'my_form_shortcodee' );
#Done conditional

function onErr() { 
    //yyy
}
$.post("test", {
    ajax: "true",
    action: ""
}).done(function(data){
    if (data == "ok"){
        //xxx
    } else if (data == "err"){
        onErr();
    }
}).fail(onErr);