How to make Twitter and Facebook correctly load your preview image

As soon as I tweeted and posted my article to Facebook, I immediately discovered that my desired preview image for my page is not properly chosen in the tweet or post article. Here's a bit of a developer tip to instruct Twitter and Facebook how to correctly to use your preferred image.

Example:

The code for both Twitter and Facebook, with Freemarker markup:

<#if content.type?? && content.type == "post">
    <#escape x as x?html>
        <meta name="twitter:card" content="summary_large_image"/>
        <meta name="twitter:site" content="@ikevin8me"/>
        <meta name="twitter:creator" content="@ikevin8me"/>
        <meta name="twitter:title" content="${content.title}"/>
        <meta name="twitter:description" content="${content.summary}"/>
        <meta name="twitter:image" content="http://ikevin.me${content.image}"/>
        <meta property="og:url" content="${content.uri}"/>
        <meta property="og:type" content="article"/>
        <meta property="og:title" content="${content.title}"/>
        <meta property="og:description" content="${content.summary}"/>
        <meta property="og:image" content="http://ikevin.me${content.image}"/>
    </#escape>
</#if>

As you can see in the code, it is important to escape the HTML.

The example code given uses Freemarker, a Java-based web templating engine, to generate the HTML dynamically. If you're using PHP or Ruby on Rails, you'll need to adapt the code properly for the HTML to be correctly generated during processing.

For more information, refer to these articles for Twitter and Facebook. And don't miss out the validators for Twitter and Facebook.