anurag-singh
12/9/2017 - 10:39 AM

WP - Add and retrieve posts data through REST API

WP - Add and retrieve posts data through REST API

// https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
// https://learnwebcode.com/wordpress-rest-api-tutorial-real-examples/

jQuery(document).ready(function($) {
	$("#update-post" ).validate({			// Form Validation rules
		rules: {
			postTitle: {
			  required: true,
			}
			,postContent: {
			  required: true,
			}
		},
	   	onkeyup: false, 					//turn off auto validate whilst typing
	    submitHandler: function (form) {	// Proccess if form validate successfully
	        insert_post();
	    }
	});

	// insert post to database
	function insert_post () {
		var title = jQuery('#postTitle').val();
		var content = jQuery('#postContent').val();

		$.ajax( {
	    	// url: wpApiSettings.root + 'wp/v2/posts/22973',
		    url: wpApiSettings.root + 'wp/v2/posts/',
		    type: 'POST',
		    beforeSend: function ( xhr ) {
		        xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
		    },
		    data:{
		        'title' : title,
		        'content' : content,
		        'status' : 'publish'
		    },
		    error: function (event, xhr, settings, exception){
		    	if ( xhr == 'error' && settings == 'Unauthorized'  ) {
			      alert( "Please login first to Add/Edit any post." );
			      return false;
			    }
		    },
		    success:function(response) {
		    	if(response.id != '') {
		    		$("#user-action-response").html("Added successfully");				// Add msg to a div
		    		$("#user-action-response").fadeToggle( "slow", "linear" );			// Visible div slowly
		    		setTimeout(function(){
		    			$("#user-action-response").fadeToggle( "slow", "linear" );		// Hide div slowly after few sec
		    		}, 3000);

		    		// load_posts();
		    		fetchPostFromDB(response.id);
		    	}
		    }

		} );
	}
	// insert post to database

	// append posts from database
	function fetchPostFromDB (postId) {

		$.ajax({
		    url: wpApiSettings.root + 'wp/v2/posts/'+postId,
		    type: 'GET',
		    beforeSend: function ( xhr ) {
		        xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
		    },
		    error: function (event, xhr, settings, exception){
		    	if ( xhr == 'error' && settings == 'Unauthorized'  ) {
			      alert( "Please login first to Add/Edit any post." );
			      return false;
			    }
		    },
		    success:function(response) {
		    	console.log(response);
		    	appendPostDataInList(response);
		    }

		});
	}
	// append posts from database

	function appendPostDataInList(response) {
		var htmlString = '';

		htmlString += '<li>' + response.title.rendered  + '</li>';
		$("#posts").prepend(htmlString);
	}


	// load posts from database
	function load_posts () {
		// $("#load-posts").click(function(){
			// alert("hi");

		$.ajax({
		    url: wpApiSettings.root + 'wp/v2/posts/?per_page=2',
		    type: 'GET',
		    beforeSend: function ( xhr ) {
		        xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
		    },
		    error: function (event, xhr, settings, exception){
		    	if ( xhr == 'error' && settings == 'Unauthorized'  ) {
			      alert( "Please login first to Add/Edit any post." );
			      return false;
			    }
		    },
		    success:function(response) {
		    	// console.log(response);
		    	createHTML(response);
		    }

		});
		// });
	}
	// load posts from database

	function createHTML(postData) {
		var htmlString = '';												// Create a empty var to hold our HTML

		for(i=0; i<postData.length; i++){									// Run the loop till its reached array length
			htmlString += '<li>' + postData[i].title.rendered + '</li>';	// Add each element value
		}

		$("#posts").append(htmlString);										// Push all the value in the container div
	}

});



<?php
	/* Template Name: Demo - REST API
 	 *	Add and retrieve posts data through REST API
 	 */
?>
<?php get_header() ?>
<div style="width: 500px">

	<form id="update-post" name="update-post">
		<input type="text" id="postTitle" name="postTitle" placeholder="Title">
		<input type="text" id="postContent" name="postContent" placeholder="Content">
		<input type="submit">
	</form>

	<div id="user-action-response" style="display: none; background-color: green;"></div>

	<div id="post-list-container">


		<?php
			$currentPage = get_query_var( 'paged' ); 			// Get var from query

			$args = array(
						'post_type' 		=> 'post'		// Custom post type
						,'posts_per_page' 	=> 2				// Max no of post to be displayed
						,'paged'			=> $currentPage		// get the current page no
					);
			$cptArr = new WP_Query($args);


			if($cptArr->have_posts()) :							// If post find in array
				echo '<ul id="posts">';

				while($cptArr->have_posts()) :					// loop till last post procsessed
					$cptArr->the_post();

					echo '<li>';
						the_title();
					echo '</li>';

				endwhile;

				echo paginate_links( array('total' => $cptArr->max_num_pages) );

				echo '</ul>';
			endif;
		?>

	</div>

</div>


<?php get_footer() ?>
<?php 
// Add REST API related scripts
function add_script_for_rest_api() {
	wp_enqueue_script('jquery-validate', get_stylesheet_directory_uri().'/assets/js/jquery.validate.min.js', array('jquery'), 1.17, true );
	wp_enqueue_script('as-wp-api', get_stylesheet_directory_uri().'/assets/js/rest-api.js', array('jquery'), 1.0, true );
	wp_localize_script( 'as-wp-api', 'wpApiSettings', array(
													    'root' => esc_url_raw( rest_url() ),
													    'nonce' => wp_create_nonce( 'wp_rest' )
													) );
}

add_action( 'wp_enqueue_scripts', 'add_script_for_rest_api' );
// Add REST API related scripts
?>