Home > Dev > WordPress SEO > Add Twitter Card Tags

Add Twitter Card Tags

This code adds Twitter Card meta tags for better Twitter sharing.

// Add this to your theme's functions.php file

function add_twitter_card_tags() {
    global $post;
    if (is_single() || is_page()) {
        echo '<meta name="twitter:card" content="summary_large_image">';
        echo '<meta name="twitter:title" content="' . get_the_title() . '">';
        echo '<meta name="twitter:description" content="' . get_the_excerpt() . '">';
        if (has_post_thumbnail($post->ID)) {
            $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
            echo '<meta name="twitter:image" content="' . esc_url($thumbnail[0]) . '">';
        }
    }
}
add_action('wp_head', 'add_twitter_card_tags');
Back