Skip to content

Instantly share code, notes, and snippets.

@brickbones
Created April 20, 2019 18:07
Show Gist options
  • Save brickbones/8c7979825f2e68f5ab021d896b81f142 to your computer and use it in GitHub Desktop.
Save brickbones/8c7979825f2e68f5ab021d896b81f142 to your computer and use it in GitHub Desktop.
WordPress page template with API (javascript and php)
<?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>';
?>
@webconnector
Copy link

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