WordPress begins with REST API – Displays other’s blogs latest posts
In this tutorial, we will learn WordPress begins with REST API – Display other blogs latest posts. You know WordPress REST API allows you to interact with your website from outside and it could be another website or mobile app. Let’s start with a very very simple example:
Also read: WordPress REST API – Create, Update or Delete posts using Basic Auth
WordPress Get Latest Posts from Blog
I created a reastapi.php file in my WordPress website directory and tested everything there.
Note: Don’t forget to require('wp-load.php')
.
<?php
# reastapi.php
require('wp-load.php');
/* Get Post */
$response = wp_remote_get( add_query_arg( array(
'per_page' => 3
), 'https://ma.tt/wp-json/wp/v2/posts' ) );
if(!is_wp_error($response) && $response['response']['code'] == 200) {
$remote_posts = json_decode($response['body']);
foreach($remote_posts as $remote_post) {
// need more parameters: print_r($remote_post)
// display post titles and post excerpts
echo '<h2>'. $remote_post->title->rendered . '</h2><p>' . $remote_post->excerpt->rendered . '</p>';
}
}
How to Disable REST API /wp-json on your Website
WordPress website default get the latest post using https://example.com/wp-json/
. So you do not want someone to interact with your website API and to get your posts without permission. In that case, you can easily disable /wp-json/
.
The below code works for WordPress 4.7 and higher, And No plugin is required.
Copy the following code snippet and paste it at the bottom of the functions.php
file:
#functions.php
add_filter('rest_authentication_errors', 'disabled_no_rest_api', 100);
function disabled_no_rest_api($access) {
if (!is_user_logged_in()) {
return new WP_Error(
'rest_not_logged_in',
__( 'You are not logged in.' ),
array( 'status' => 401 )
);
}
}
The REST API is now disabled for users. Now test this, Open the web browser to go to https://example.com/wp-json/wp/v2.
Output
{"code":"rest_not_logged_in","message":"You are not logged in.","data":{"status":401}}
tnx very good