Last active
September 24, 2018 06:21
-
-
Save michaelbrazell/a0d1fcd8ae8d3fd4ab97 to your computer and use it in GitHub Desktop.
Using WP REST API to Loop through Custom Post type with JSON
This file contains hidden or 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
<html> | |
<head> | |
<title>Looping through json object</title> | |
<script type="text/javascript"> | |
/* | |
Looping through your custom post type data using Wordpress rest API | |
You'll need this plugin as of 1/15/2015. http://wp-api.org/ | |
Eventually this will be included in the WP Core. Supposed to be with 4.1, but that didn't happen. | |
*/ | |
</script> | |
<script type="text/javascript"> | |
var xhr = new XMLHttpRequest(); | |
xhr.onload = function() { | |
if(xhr.status === 200) { | |
responseObject = JSON.parse(xhr.responseText); | |
// Build up strings | |
var newContent=''; | |
for (var i = 0; i < responseObject.length; i++) { // Loop through items | |
newContent += '<ul class="items">'; | |
newContent += '<li><strong>Title:</strong> ' + responseObject[i].title + '<br><strong>ID:</strong> ' + responseObject[i].ID + '</li>'; | |
newContent += '</ul>'; | |
} | |
// Update page | |
document.getElementById('container').innerHTML = newContent; | |
} | |
}; | |
// Your post type name goes here after ?type | |
// Alternatively, you could loop through all posts by dropping the query string | |
xhr.open('GET', '/wp-json/posts?type=custom-post-type-name', true); | |
xhr.send(null); | |
</script> | |
</head> | |
<body> | |
<h1>Custom Post Type Content</h1> | |
<p>Display your content here</p> | |
<div id="container"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how features images for custom post type?