Several versions ago, WordPress introduced a rest API that allows content to be accessed externally. Adding an API is a very powerful tool because it allows us to easily extend our web offering to applications such as Android or iOS.
With the WordPress API we can make the following requests:
- GET: Allows you to retrieve data such as posts, entries, users, and other data.
- POST: Allows you to send data to create content.
- PUT: Allows data to be updated based on the content sent.
- DELETE: Allows content to be deleted.
However, by default these requests are for the data types included in WordPress by default (Post, Pages, Users, etc...), but in this article, in addition to seeing how to access this data, we will explain how to create our own endpoint to query and insert our Custom Post Types.
Creating API access credentials
To access the API, you need to create Username/Password credentials so that requests are not rejected. For the example in this article, we will use the plugin "Application Passwords" which allows us to create a password for the WordPress user without exposing their password for accessing the WordPress panel.
To add the plugin, go to Plugins -> Añadir nuevo and in the search bar type "Application Passwords" and install and activate the plugin.
Once the plugin is activated, go to Usuarios and select the user you want to grant API access to. Creating a new user for this is advisable, since using the WordPress "admin" user is not recommended.
In the user's profile, you will see that a new section has been added called "Application Passwords", where you must enter a descriptive title for the new password and click "Add New".
Once you click "Add New", you must save the password displayed, since this is what you will use to authenticate. For our example, the credentials would be username: clouding and password Dfjp KptN ogp2 1Ytv Hq48 HPzy.
This gives us the foundation for accessing the WordPress API.
Retrieving and creating Posts with the WordPress API
For the example, we will use the tool Postman which will allow us to easily test how our API works. If you are unfamiliar with it, you can download it at this link https://www.postman.com/.
The URL to which we must send requests is "https://midominio.com/wp-json/wp/v2/posts". We can replace "Posts" with the following options, among others included in WordPress by default:
| Name | Path |
|---|---|
| Categories | /wp/v2/categories |
| Tags | /wp/v2/tags |
| Pages | /wp/v2/pages |
| Users | /wp/v2/users |
| Post Types | /wp/v2/types |
You can consult the remaining endpoints at the following link https://developer.wordpress.org/rest-api/reference/.
Retrieving the list of posts from our WordPress site
Now open Postman and click "New Collection".
Specify a name and a description and click Create.
Now create a new Request.
Enter a title and a description and click Save.
Select the new Request from the menu on the left and add the URL to which we will make the request of type GET and in the Authorization section choose the type Basic Auth and add the credentials created earlier.
Click send and it will return JSON like the following, where you can see information such as the post ID, title, and content.
Creating a post on our WordPress site
In Postman create a new Request as we did earlier. Specify the URL, but this time change the type from GET to POST.
Fill in the Authorization section again as we did earlier:
Since we need to send data to the API, now select Body -> raw -> JSON. We will create JSON like the following, specifying the title and content.
Once you have specified the data to send to the API, click Send and you will get a response like the following:
We can verify in the WordPress administration panel that the Post was created successfully.
We can add parameters to our Request to publish it automatically, insert the category, tags, etc...
With these simple steps, we have seen how to access our WordPress through the API to retrieve and insert data from an external application.
Creating a Custom Post Type
To create a Custom Post Type for the example, go to Aparencia -> Editor de Temas and open the file functions.php. In this file, we will add the following code, which creates a type "servidoresVps" where we will add a "TextBox" to specify the IP address of our servers. The function for saving the data to the WordPress database is also specified.
We also specify the variable "show_in_rest" with a value of "true" so that it can be accessed through the WordPress API, and enable "custom-fields" so we can add our own fields.
<?php
add_action( 'init', 'registrar_custom_post_type' );
function registrar_custom_post_type() {
$labels = array(
'name' => _x( 'Servidores VPS', 'post type general name', 'text-domain' ),
'singular_name' => _x( 'Servidor VPS', 'post type singular name', 'text-domain' ),
'menu_name' => _x( 'Servidores VPS', 'admin menu', 'text-domain' ),
'add_new' => _x( 'Añadir nuevo', 'servidor', 'text-domain' ),
'add_new_item' => __( 'Añadir nuevo servidor', 'text-domain' ),
'new_item' => __( 'Nuevo servidor', 'text-domain' ),
'edit_item' => __( 'Editar servidor', 'text-domain' ),
'view_item' => __( 'Ver servidor', 'text-domain' ),
'all_items' => __( 'Todos los servidores', 'text-domain' ),
'search_items' => __( 'Buscar servidor', 'text-domain' ),
'not_found' => __( 'No hay servidores.', 'text-domain' ),
'not_found_in_trash' => __( 'No hay servidores en la papelera.', 'text-domain' )
);
$args = array(
'labels' => $labels,
'description' => __( 'Descripción.', 'text-domain' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'libro' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'show_in_rest' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields')
);
register_post_type( 'servidoresVps', $args );
}
function informacion_vps_metabox() {
add_meta_box( 'informacion-vps', 'Datos técnicos del servidor', 'informacion_vps_box_content', 'servidoresVps', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'informacion_vps_metabox' );
function informacion_vps_box_content( $post ) {
$values = get_post_custom( $post->ID );
$ip = isset( $values['info_vps_ip'] ) ? esc_attr( $values['info_vps_ip'][0] ) : '';
?>
<p>
<label for="info_vps_ip">IP del servidor</label>
<input type="text" name="info_vps_ip" id="info_vps_ip" value="<?php echo esc_html( $ip ); ?>" />
</p>
<?php
}
add_action( 'save_post', 'informacion_vps_metabox_save' );
function informacion_vps_metabox_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! current_user_can( 'edit_post' ) ) {
return;
}
if ( isset( $_POST['info_vps_ip'] ) ) {
update_post_meta( $post_id, 'info_vps_ip', wp_kses( $_POST['info_vps_ip'], $allowed ) );
}
}
Once we save the file, our new type will appear in the left sidebar menu.
If we create a new record, the text field for entering the "Ip del servidor" will appear.
Exposing Custom Post Types to the WordPress API to insert data
The first thing we will do to insert data through the API is register our own route with the method POST. We must insert the following code in Aparencia -> Editor de Temas -> functions.php. This will declare the URL midominio.com/wp-json/api/v1/insertar_vps.
add_action( 'rest_api_init', function() {
register_rest_route( 'api/v1','/insertar_vps', [
'methods' => 'POST',
'callback' => 'insertar_vps'
] );
} );
Now we need to create the callback function that will insert the received data into the WordPress database. To do this, create the following function:
function insertar_vps($data){
$parameters = $data->get_params();
$my_post = array(
'post_title' => $parameters['post_title'],
'post_content' => $parameters['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'servidoresVps',
'meta_input' => array(
'info_vps_ip' => $parameters['info_vps_ip'],
)
);
$idPost = wp_insert_post( $my_post );
if($idPost != 0){
return "OK";
};
return "KO";
}
If we open Postman as we did earlier, we can test inserting data by creating a new Request like the following:
We can see the result on our WordPress site by clicking in the left sidebar menu on Servidores VPS. As we can see in the following images, it has saved the data we passed in the request sent to the API.
Finally, we will create the functions to retrieve the list of Posts of type servidoresVPS that we created. To do this, we will create a new API route and a new callback that will return the posts.
add_action( 'rest_api_init', function() {
register_rest_route( 'api/v1','/obtener_vps', [
'methods' => 'GET',
'callback' => 'obtener_vps'
] );
} );
function obtener_vps() {
$args = [
'numberposts' => 10,
'post_type' => 'servidoresVps',
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['info_vps_ip'] = $posts[0]->info_vps_ip;
return $data;
}
We can test this in Postman by creating a new Request of type GET specifying the new route. As we can see in the following image, it has returned the Post created in the previous example.
With the steps taken in this article, we have seen how to extend the functionality of our WordPress website so that it is accessible from other platforms, such as an Android or iOS APP.