Forked from brickbones/wordpress-page-temaplate.php
Created
January 14, 2022 18:02
-
-
Save iamshacky/d708deb2f2197e950fdeb36e30aed550 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>'; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment