Since around mid-2012, Twitter has supported Twitter Cards. Twitter Cards are meant to give Twitter users a preview of posted links. You can present video, images, or text snippets as a preview. The following code lets WordPress users optimize their theme for Twitter Cards.
First, add the following code to the function.php of your WordPress theme; once you’ve done that, you still need to apply for Cards with Twitter registrieren.
Once Twitter has given the okay, the Twitter Cards will appear automatically when someone posts one of your articles on Twitter.
//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 des Blogs
echo '<meta name="twitter:creator" content="SumTips"/>'; //optional: Username des Autors
if(!has_post_thumbnail( $post->ID )) { //Bild das angezeigt werden soll, wenn es kein Artikelbild gibt
$default_image="http://example.com/image.jpg"; //gib hier die URL für das Alternativbild an
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');
One last quick summary of the code. The code takes an excerpt of your post, uses your name as the author, and uses the post’s featured image. If no featured image is present, you need to provide an alternative image in the code. The entire code is then loaded into the of your theme when the page is requested.
The text was automatically translated from German into English. The German quotations were also translated in sense.
Want to reply?
Send me a note via email and let's start a conversation. You can also follow along via RSS or Mastodon.