Embed list of WordPress articles in your website

WordPress provides a WYSIWYG (What You See Is What You Get) interface that’s pretty useful, but what if you want to customize it a little bit more? Especially exploiting the wordpress back-end only and use your website interface?

I wanted to show the list of my articles using my interface as you can see here: http://lucavallarelli.altervista.org/blog.html showing contents coming from the list of articles I’ve written in wordpress environment.

The trick is around building the link below:

http://<yourBlog>/wp-json/wp/v2/posts

This link will give you a json containig all information about your posts including their content, therefore you’ll have an array of data and metadata, so it will be possible to cycle through that array and show whatever information about all the articles. In my case is: http://lucavallarelli.altervista.org/blog/wp-json/wp/v2/posts.
If you try to open it in the browser it might seems a mess but it’s a json, so you can use whatever “beautify” feature of a text editor or an online service to realize that that’s the list of article with many properties.

Here the code that doesn’t use any online services but it’s a pure straight forth javascript snippet which takes the json and print a simple list of the Title, part of the article’s content and the link to open it.

<!DOCTYPE html>
<html lang="en">
<head>
<title>List my wordpress posts in my website</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <div class="mypanel"></div>
<script>   
   var site = 'http://lucavallarelli.altervista.org/blog/wp-json/wp/v2/posts'
$.getJSON(site, function(data) {
    var text = ""
    var i;
    for (i = 0; i < data.length; i++) { 
          text += 
        "<b>"+data[i].title.rendered+"</b>"
        +"<br>"
        + data[i].content.rendered.substring(4, 200)
        +"...<a href='"+ data[i].link +"'>Read full article</a><br><br>" ;
    }          
    $(".mypanel").html(text);
});
</script>
</body>
</html>

Whatch out! If you test this outside of your website domain it can give you CORS error, so instead of dealing with how to by pass it, simply put the code in a folder of your website or a dev website for your test.

Take that snippet as it is and change the “site” variable with your link (
<http://link-where-your-blog-is/wp-json/wp/v2/posts> ), and it will work already.

1 thought on “Embed list of WordPress articles in your website”

Leave a Comment

Your email address will not be published. Required fields are marked *