Created
April 20, 2019 18:07
-
-
Save brickbones/8c7979825f2e68f5ab021d896b81f142 to your computer and use it in GitHub Desktop.
WordPress page template with API (javascript and php)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php /* Template Name: Awesome Page */ | |
get_header(); | |
?> | |
<div class="latest-posts"></div> | |
<script> | |
const url = 'http://localhost:8888/ieatwebsites-v2/wp-json/wp/v2/posts'; | |
const postsContainer = document.querySelector('.latest-posts'); | |
fetch(url) | |
.then(response => response.json()) | |
.then(data => { | |
data.map( post => { | |
const innerContent = | |
` | |
<li> | |
<h2>${post.title.rendered}</h2> | |
${post.excerpt.rendered} | |
<a href="${post.link}">Read More</a> | |
</li> | |
` | |
postsContainer.innerHTML += innerContent; | |
}) | |
}); | |
</script> | |
<?php | |
$response = wp_remote_get( 'http://localhost:8888/ieatwebsites-v2/wp-json/wp/v2/posts' ); | |
$posts = json_decode( wp_remote_retrieve_body( $response ) ); | |
echo '<div class="latest-posts">'; | |
foreach( $posts as $post ) { | |
echo '<li><h2>'.$post->title->rendered.'</h2>'.$post->excerpt->rendered.'<a href="' . $post->link . '">Read More</a></li>'; | |
} | |
echo '</div>'; | |
?> |
Can you use this to get post from other WordPress sites that are not yours too?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is nice