Search code examples
javascriptapijquerytumblr

Using Tumblr API to pull first sentence from post captions


I've got a quick question regarding the Tumblr API. I'm working on a website for a photographer and would like to use that API to stream the first 50 - 100 words from her two most recent posts on her homepage. The JS file I've written streams the captions from the two most recent posts, but I can't figure out how to pull only the first fifty or so words. Any advice would be greatly appreciated!!

function buildURL (blogname, apiKey) {
    return 'http://api.tumblr.com/v2/blog/'
        + blogname
        + '.tumblr.com/posts?api_key='
        + apiKey
        + '&limit=2'
        + '&callback=?'
}

var key = '/* Put your Tumblr Key Here */'

var url = buildURL('ehockstein', key)

$(function () {
    $.getJSON(url, function (data) {

        console.log(data)

        createPosts(data.response.posts)

    })
})

function createPosts (posts) {

    posts.forEach(function (post) {

        var postElement = $('<div class="post"></div>')
        postElement.addClass(post.type)

        if (post.type === 'photo') {

            var caption = post.caption

            postElement.append(caption)

        }

        postElement.appendTo('#tumblr-posts')

    })
}

Solution

  • The Tumblr API doesn't support returning partial captions. You'll need to pull the full caption from the API and create a substring in your own code that contains the first 50 - 100 words.

    This would look something like this:

    var shortCaption = caption.substring(0, 499)
    

    That takes the first 500 characters, which will give you close to 100 words.

    You could then append shortCaption to postElement (as opposed to appending caption).

    You can learn more about how substring works here.