Begin with REST API – Display others blogs latest posts

When REST API appeared in WordPress, the enormous amount of tutorials are appeared too. But are those tuts good, clear and easy to understand?

#httpapi, #restapi  /    /   10

As you maybe heard, REST API allows to interact with your WordPress website from outside and it could be another website or mobile app.

Latest Posts from Matt Mullenweg’s Blog #

Matt is the founder of WordPress. Oh, really, is that possible to get his posts? 😲 Let’s look at a very very simple example:

// connect to the website endpoint with wp_remote_get() function
// pass params as URL query args, full parameter list is here https://developer.wordpress.org/rest-api/reference/posts/
// at this moment you can use any parameter with Context: View
// it would be strange if you can fetch drafts or private posts, right?
$response = wp_remote_get( add_query_arg( array(
	'per_page' => 2
), 'https://ma.tt/wp-json/wp/v2/posts' ) );
 
if( !is_wp_error( $response ) && $response['response']['code'] == 200 ) {
 
	$remote_posts = json_decode( $response['body'] ); // our posts are here
	foreach( $remote_posts as $remote_post ) {
 
		// display post titles and excerpts
		echo '<h2>'. $remote_post->title->rendered . '</h2><p>' . $remote_post->excerpt->rendered . '</p>';
		// need more parameters? print_r( $remote_post )
 
	}
}

If you have experience with Instagram or MailChimp API for example, the above code should be awesomely simple for you.

Posts from Two and More Blogs in Chronological Order #

Sometimes you may need to get posts from several blogs, for example for your “Latest WordPress News” widget. It is possible to do with WordPress REST API + HTTP API but transient cache is highly recommended.

// trying to get value from the cache
if( false == $allposts = get_transient( 'misha_remote_cache' ) ) {
 
	// it will be the array with all posts
	$allposts = array();
 
	// get the first website latest posts
	$blog1 = wp_remote_get( 'https://ma.tt/wp-json/wp/v2/posts?per_page=2' );
 
	if( !is_wp_error( $blog1 ) && $blog1['response']['code'] == 200 ) {
 
		$remote_posts = json_decode( $blog1['body'] ); // our posts are here
		foreach( $remote_posts as $remote_post ) {
 
			// I decided to create array like $allposts[1504838841] = Object
 			$allposts[ strtotime( $remote_post->date_gmt ) ] = $remote_post;
 
		}
	}
 
	// get the second website latest posts
	$blog2 = wp_remote_get( 'https://css-tricks.com/wp-json/wp/v2/posts?per_page=2' );
 
	if( !is_wp_error( $blog2 ) && $blog2['response']['code'] == 200 ) {
 
		$remote_posts = json_decode( $blog2['body'] ); // our posts are here
		foreach( $remote_posts as $remote_post ) {
 
 			$allposts[ strtotime( $remote_post->date_gmt ) ] = $remote_post;
 
		}
	}
 
	// sort array by keys in descending order
	krsort( $allposts );
 
	// store cache
	set_transient( 'misha_remote_cache', $allposts, 60 ); // for 1 minute in this example
 
}
 
// print posts
foreach( $allposts as $remote_post ) {
	echo '<h2>'.$remote_post->title->rendered.'</h2><p>' . $remote_post->date_gmt . '</p>';
}

I created php file in my website directory and tested everything there. But in this case do not forget to require('wp-load.php').

Get Posts with Rest API from the other blogs

How to Completely Disable REST API /wp-json on your Website #

Well, what if you do not want someone to interact with your website API and to get your posts without permission? 😂 So, in that case you can easily disable /wp-json/

This code works for WordPress 4.7 and higher, no plugin required.

add_filter( 'rest_authentication_errors', 'misha_no_rest_api_4_7' );
 
function misha_no_rest_api_4_7( $access ) {
 
	return new WP_Error( 'rest_cannot_access', 'Soooooryyyy', array( 
		'status' => 403 
	) );
 
}
It is how to completely disable REST API in WordPress

In the next tutorial about REST API we will talk about authorization.

Misha Rudrastyh
About the author Misha Rudrastyh

Passionate about WordPress and snowboarding, creating websites for over 10 years! Let's work together — just contact me.

If you are a developer too, subscribe to my facebook page.

Comments 10

  • Hi Misha,

    Can we not just turn OFF REST API in WooCommerce settings?

    You may ALSO want to add that we should disable WordPress REST API as well in order to make our data completely secure!

    Thanks.

    • Hi,

      Sorry for delay in replying – do you mean to disable REST API for WordPress without disabling WooCommerce API?

      • No, I meant in order to gain complete security, we should disable BOTH WooCommerce API as well as WordPress REST API.

        Since I am also learning about WordPress / Woocommerce, please share your knowledge on achieving this.

        Thanks.

        • But this code from the post disables both WooCommerce and WordPress REST API, so just try to access this Woo API endpoint https://rudrastyh.com/wp-json/wc/v2/orders.

          • Thanks Misha, perhaps I did not check properly. I also was checking for

            https://rudrastyh.com/wc-api/v3/
  • Hello dear,
    Thank you for your great article, i enjoy it so much, it is easy to read,
    so right now, i want to know from you, how to use client API key in wordpress site,
    i mean that where to start working 1st.? you have written “Latest Posts from Matt Mullenweg’s Blog”
    below codes, that was really great, but i’m confuse that, which file i should write this codes? please ans to me ASAP i’m waiting for your great response, as i’m a beginner, my client is wanting some categories posts can show his site,

    Thank you so much,

    • MishaAuthor

      Hello,

      No API key is required in this case, you just have to specify a correct endpoint URL. You can insert this code in the place where you would like to show the posts.

  • Thanks Misha,

    I tested your code and when i try to get posts from my website (https://he.savvy.co.il/blog/wp-json/wp/v2/posts) i get a 403 error.

    But if i check that same URL from the browser i get 200 response… How come? what am i missing?

  • Thank you – very well done!

Comments are closed.
If you need my personal help, please contact me. Contact me