How To Add Twitter Cards To WordPress

Sharing previews are yet another thing missing from WordPress which should really be included by now. It’s dead easy to install a plugin and have it all done for you, but why bother with slowing down your site with needless plugins when you can add a tiny bit of code to your functions file.

add_action('wp_head', 'add_twitter_cards');

function add_twitter_cards() {
    if(is_single()) {
        $tc_url    = get_permalink();
        $tc_title  = get_the_title();
        $tc_description   = get_the_excerpt();
        $tc_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), full );
        $tc_image_thumb  = $tc_image[0];
        $tc_author   = str_replace('@', '', get_the_author_meta('twitter'));
        ?>
        <meta name="twitter:card" value="summary" />
        <meta name="twitter:site" value="@elegantthemes" />
        <meta name="twitter:title" value="<?php echo $tc_title; ?>" />
        <meta name="twitter:description" value="<?php echo $tc_description; ?>" />
        <meta name="twitter:url" value="<?php echo $tc_url; ?>" />
        <?php if($tc_image) { ?>
            <meta name="twitter:image" value="<?php echo $tc_image_thumb; ?>" />
            <?php } if($tc_author) { ?>
                <meta name="twitter:creator" value="@<?php echo $tc_author; ?>" />
                <?
            }
    }
}

Simply paste in the above code to the functions.php file in your WordPress theme and validate all has gone correctly using the Card Validator.