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 ‘’;
 echo ‘’;
 echo ‘’;
 echo ‘’;
 echo ‘’; //optional: username of website
 echo ‘’; //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 ‘’;
 }
 else{
 $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), ‘medium’ );
 echo ‘’;
 }
 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.

Comments

via webmention
✴️ Also on Micro.blog

You might also like