Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamshacky/d708deb2f2197e950fdeb36e30aed550 to your computer and use it in GitHub Desktop.
Save iamshacky/d708deb2f2197e950fdeb36e30aed550 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>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment