[API] Begin with REST API – Display others blogs latest posts

https://rudrastyh.com/wordpress/rest-api-get-posts.html

Ví dụ 1:

C:\xampp\htdocs\wordpress\wp-content\themes\twentytwentyone\header.php

<?php  
				// 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,
				  ), 'http://localhost/wordpress/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 '<div>' . $remote_post->title->rendered . '</div>';
				    // need more parameters? print_r( $remote_post )
				  }
				}
			?>

Ví dụ 2:

C:\xampp\htdocs\wordpress\wp-content\themes\twentytwentyone\header.php

Begin with REST API – Display others blogs latest posts

Updated on Jul 23rd, 2019 in

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:

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.

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.

It is how to completely disable REST API in WordPress

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

Last updated

Was this helpful?