The Gloat Blog

How to show your latest Ghost blog post on your homepage

A quick tutorial for adding live-updating blog posts to any web page using the Ghost API and some Javascript.

· Dan Rowden

The Ghost Content API is an amazing tool, which lets you pull out public data from your Ghost site.  In this tutorial, we're going to use some Javascript to display a blog's latest post on a web page.

Here's a good example of what I mean, from Fathom:

Step 1: Create an integration and get an API key

Go into your Ghost admin, head to Integrations and create a new custom integration.

Then note the Content API key. You will need this to access the API from your web page.

Note: this API key allows read-only access to public data from your Ghost site. Anyone can uses this API key to programatically pull out public data from your site and use it elsewhere.

Step 2: Add some Javascript to your web page

Now that the API is all set up, we can add the code that will pull in and display the blog post.

Ghost's Content API has a lot of parameters you can use to change the data returned.

In this example, I've limited the number of posts returned to just one (posts are returned in reverse chronological order by default), and I've only requested the title and URL, as that's all we need for this tutorial.

https://testdomain.com/blog/ghost/api/v3/content/posts/?key=238ff0a0909c5b17c34b40a79a&fields=title,url&limit=1

Once you've got your own API key and if you use your own domain, you can put this URL into your browser to test the data that is returned.

Now, we just need to paste in some Javascript into our web page to display the post information. It's best to put this towards the bottom of your page.

<script>
    fetch('https://testdomain.com/blog/ghost/api/v3/content/posts/?key=238ff0a0909c5b17c34b40a79a&fields=title,url&limit=1')
    .then(response => response.json())
    .then(result => {
      let post = result['posts'][0]
      document.getElementById('blogPost').innerHTML = `<a href="${post.url}" target="_blank" class="tdn">${post.title}</a>`
    })
</script>

This code simply wraps the post title in a link and adds this into an HTML element with the id blogPost. You can of course use any element in your page, and now that you have the data, it's easy to style the link with CSS.

For more options for the Ghost API call, check out the Ghost Content API documentation. You could display the feature image, date or excerpt by adding a few more values to the fields parameter, or show a list of latest posts changing the limit parameter.