Search code examples
pythontumblrtwitter-cardpytumblr

How to add meta tags to Tumblr API's blog header?


The Tumblr API is really impressive as it allows me to publish directly into the blog. However I would like to add meta for Twitter card as well. Is there any way to achieve this?

       client = pytumblr.TumblrRestClient(
            app.config['CONSUMER_KEY'],
            app.config['CONSUMER_SECRET'],
            app.config['OAUTH_TOKEN'],
            app.config['OAUTH_SECRET'],
        )
        if news.is_published:
            body = ''
            if news.image_url_list and len(news.image_url_list) > 0:
                body = '<img src="{0}" /><br/>'.format(news.image_url_list[0])
            slug = Slugify.slugify(news.head_line)
            post = client.create_text("xxx.tumblr.com",
                                      state="published",
                                      tags=news.tag_list,
                                      format='html',
                                      slug=slug,
                                      title=news.head_line,
                                      body=body + news.summary.encode('utf-8'))

How do I add these meta tags to the blog post?

<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@flickr" />
<meta name="twitter:title" content=? news.head_line ? />
<meta name="twitter:description" content=? news.description ? />
<meta name="twitter:image" content=? news.image_url_list[0] ? />

Solution

  • The Tumblr API doesn't support adding arbitrary metadata to posts, but you can add the meta HTML elements you desire to the blog post output served to visitors by reusing the content already stored in Tumblr and adding the appropriate Tumblr markup.

    Go to Tumblr, your account, your Tumblr blog, "Edit Appearance", "Edit theme", "Edit HTML", and add a block of output that only executes on post pages:

    <html>
        <head>
            <!-- ... -->
    
            <!-- Only show on permalink pages (blog post) -->
            {block:PostTitle}
                <!-- Iterate over all post types -->
                {block:Posts}
                    <!-- For Link posts, output this -->
                    {block:Link}
                        <meta name="twitter:card" content="summary" />
                        <meta name="twitter:site" content="@example" />
                        <meta name="twitter:title" content="{Name}" />
                        <meta name="twitter:description" content="{Description}" />
                        <meta name="twitter:image" content="{Thumbnail-HighRes}" />
                    {/block:Link}
                {/block:Posts}
            {/block:PostTitle}
    
            <!-- ... -->
        </head>
        <body>
            <!-- ... -->
        </body>
    </html>
    

    You'll need to add additional {block:Something} Tumblr template tags for each post type. This example will only support Link posts.