I have a fully functional Wordpress site and I want the to create a new separate website that displays the posts from the wordpress site using the Wordpress Rest API. I understand that typing http://my-website/wp-json/wp/v2/posts into a browser shows me this information but I want to code it into the new separate site. I don't even know where to start! Does anyone know how to help?
2 Answers
You'll want to use cURL to do server to server connections. There are plenty of examples online but here is a good starting point so you can at least know what functions to look into.
-
Please provide a CURL example then on how to do this. Commented May 18, 2016 at 19:44
You could use a function like the following and call it like my_prefix_fetch_data( 'posts?per_page=3' )
or my_prefix_fetch_data( 'categories' )
.
if ( ! function_exists( 'my_prefix_fetch_data' ) ) {
function my_prefix_fetch_data( $query ) {
$response = wp_remote_get( esc_url_raw( 'http://my-website/wp-json/wp/v2/' . $query ) );
if ( is_wp_error( $response ) ) {
return array();
}
$output = wp_remote_retrieve_body( $response );
$output = json_decode( $output );
if ( empty( $output ) ) {
return array();
}
return $output;
}
}