How can I show WP posts to HTML static page?
I already know for WP singal site this code works fine which is given in this tutorial:
https://www.cocoonfxmedia.co.uk/blog/displaying-wordpress-posts-in-html-page
this working fine for singular site
But this code is not working for wp multisites its giving "Database connecting error
"
You can get the posts of your wordpress website with the rest api and use javascript to display the posts on a static html website.
I will give you a code example using Vue JS.
On your html page, you include vue js with adding this to your <head>
section:
<!-- development version, includes helpful console warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
That's all you have to do to use vue js, great.
Now we need a javascript file, for example call it app.js
and include this at the bottom of your html page using:
<script src="app.js"></script>
Inside of this app.js
file you are getting the posts and saving it to posts: []
. Put this code inside of the javascript file:
new Vue({
el: '#posts',
data: {
posts: [],
},
mounted() {
fetch("https://yourWordpressURLhere.com/wp-json/wp/v2/posts?per_page=20&_embed=wp:term,wp:featuredmedia")
.then(response => response.json())
.then((data => {
this.posts= data;
}))
}
});
In this code, we create a new vue instance and assign it to the element with id #posts
, we then get the data from the wordpress page inside of fetch
and use &_embed
to also get the featured image and the post terms (maybe you need this in your output).
For your reference, if you need to get other post types: https://developer.wordpress.org/rest-api/reference/
So we now have our posts in the data
object. We can now use this data in our html page inside the div with the id #posts
. You have to include the following code inside of the <body>
of your html page:
<div id="posts">
<div v-bind:key="post.title.rendered" v-for="post in posts">
<a v-bind:href="post.link"><img v-bind:src="post._embedded['wp:featuredmedia']['0'].media_details.sizes.medium_large.source_url"></a>
<a v-bind:href="post.link"><h4 v-html="post.name"></h4></a>
<p v-html="post.title.rendered"></p>
</div>
</div>
The v-for
loops through your post and will always display the div container with a featured image (in medium size) and post titles, linked to the detail page of the post.
So with using wordpress as a backend and vue js as frontend javascript framework, you can show your wordpress posts on a static html page.
Of course there are other ways using Rest API and showing wordpress posts with javascript. But Vue JS is a state of the art framework and has a very good performance, so I would recommend using it.