Greg Morris

Follow @gr36 on Micro.blog.

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 Twitter Cards Meta Info
function add_twitter_card_info() {
    global $post;
    if ( !is_singular())
        return;
    echo '<meta name="twitter:card" content="summary"/>';
    echo '<meta name="twitter:url" content="' . get_permalink() . '"/>';
    echo '<meta name="twitter:title" content="' . get_the_title() . '"/>';
    echo '<meta name="twitter:description" content="' . get_the_excerpt() . '"/>';
    echo '<meta name="twitter:site" content="SumTips"/>'; //optional: username of website
    echo '<meta name="twitter:creator" content="SumTips"/>'; //optional: username of content creator
    if(!has_post_thumbnail( $post->ID )) { //use a default image if no featured image set
        $default_image="http://example.com/image.jpg"; //replace this with a default image
        echo '<meta name="twitter:image" content="' . $default_image . '"/>';
    }
    else{
        $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
        echo '<meta name="twitter:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
    }
    echo "\n";
}
add_action( 'wp_head', 'add_twitter_card_info');

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.