domingo, 29 de agosto de 2021

How to use API REST with wordpress

In this article I will show You how to use API REST with WordPress. This is the best way for not create script php for (insert, delete, update by Ajax). All will be simple with API REST.

Requirements

  1. PHP 7
  2. Wordpress 5.7
  3. You must be logged into WordPress (important for follow the next instructions)

We will use the API REST WordPress in the following tasks: 

1. List comments
2. Create comments

1. List Comments

 For use the API, We will need to read the documentation of basic authentication and apply.

Now add in `function.php` the following script. With this we have acces to the variable global `jsVars` in all page. the principal variable es jsVars.wp_nonce

  wp_localize_script( 'jquery', 'jsVars', [
    'ajax_url'    => admin_url( 'admin-ajax.php' ),
    'api_rest_url'=> get_rest_url(),
    'wp_timezone' => wp_timezone(),
    'wp_user'     => wp_get_current_user(),
    'wp_nonce'    => wp_create_nonce( 'wp_rest' ),
    'wp_lang'     => get_locale()
  ]);

Here a example using jQuery Ajax.

GET http://example.local/wp-json/wp/v2/comments?post=2253

List all comments on the post

$.ajax( {
    url: jsVars.api_rest_url + 'v2/comments?post=1',
    method: 'GET',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', jsVars.wp_nonce );
    }
} ).done( function ( response ) {
    console.log( response );
} );

 

 2. Create Comments

For make this request the URL will be:

POST http://example.local/wp-json/wp/v2/comments

Here a other example using Jquery Ajax

jQuery.ajax({
	url : jsVars.api_rest_url + 'wp/v2/comments',
	type : 'POST',
	dataType:'json',
	data: {
		"post": 1,
		"content": "this is a example comment",
		"author": jsVars.wp_user.ID
	},
	beforeSend: function(xhr) {
		xhr.setRequestHeader( 'X-WP-Nonce', jsVars.wp_nonce );
	},
	success : function(data) {
		console.log('data', data);
	}
});


If you need use POSTMAN for any reason. you must be copy the Header of HTTP. You can do it following the next steps. and before you can to make fast and easy many request REST (GET,POST and OTHER).



No hay comentarios.:

Publicar un comentario