Age of Article Warning: This article was originally published a few years ago. The information, tips and techniques explained may outdated. Examples shown on this page may no longer work. Please consider this when viewing the below content.

Make your website links stand out in the Twitter stream with Twitter Cards. [dtwd-tweet text="Make your website links stand out in the Twitter stream with Twitter Cards" hashtags="TwitterCards, WordPress"]This is an updated version of my original Twitter Card post from April last year. I decided to add more value with some functions to automate your Twitter Cards. This code will enable you to use the following 3 types of Twitter Cards:

[cposhort_list icon="twitter" style="round"]Summary Cards[/cposhort_list][cposhort_list icon="twitter" style="round"]Large Image Summary Cards[/cposhort_list][cposhort_list icon="twitter" style="round"]Photo Cards[/cposhort_list]

What are Twitter Cards?

When you have Twitter Card markup on your website, then when a Twitter user tweets your post or page, a special card is attached to that tweet, that is visible to their followers. So in a Twitter stream, when a link from your website appears in a Tweet, there is an option to click on the card to expand.Here are some examples of the 3 cards we will be setting up:

Summary Card:

The Twitter Summary Card is designed to give the reader a preview of the content by displaying a small image and summary below the 140 characters.

How to show #WordPress Gallery in a Lightbox using FancyBox http://t.co/5ldpiFDR3d— David Tiong (@MrDavidTiong) November 25, 2014

Summary Card with Large Image:

This Large Image Summary Card displays a large, full-width image with the tweet, to make your featured image stand out along with the summary and link to your website.

Working on a new post at http://t.co/WKIk5KRfp0 - Adding Twitter Cards to your website - coming soon — David Tiong (@MrDavidTiong) November 26, 2014

Photo Card:

The Twitter Photo Card put the focus on the image, richer and in more detail puts the image front and center in the Tweet.

For help with promoting your business online we offer a great range of services - designed to help you http://t.co/IpZEKrgyPJ— David Tiong (@MrDavidTiong) November 26, 2014


So now it's time to add this cool feature for your website links on Twitter.

First we'll cover the key meta fields that need to go into your page header so that Twitter can identify the correct card, image and information.There are 6 key fields that are common and will look something like this:<meta name="twitter:card" content="summary" />

<meta name="twitter:site" content="@mrDavidTiong" />

<meta name="twitter:title" content="The page title" />

<meta name="twitter:description" content="The page description" />

<meta name="twitter:image" content="my-image-url.jpg" />

<meta name="twitter:url" content="The page url" />

If you want to review the documentation, then you can read up on the different Twitter Cards type here.Now we want to automate as much as possible so that we don't have to type in this header code for each post or page on our website. The following function will extract the data from your website based on featured images, excerpts or page content, and you can also choose on a page by page basis which card you want to display. [dtwd-tweet text="WordPress function to add Twitter Cards to your Website" hashtags="TwitterCards, WordPress"]Copy the code below and paste into your childtheme's functions.php file or your mu-plugin file. The code sets a default Summary Twitter Card for posts and pages. It adds the Twitter handle, the page title, a page description, an image and the page url. There are important notes below the code explaining further.//add Twitter card function information

function add_twitter_card_information() {

   global $post;

   $twit_card_type='summary';

   $twit_pic='';

   $twit_description='';

   if (is_single() || is_page()) {

       if(get_post_meta($post->ID,'cardtwitter_type',true) !='') {

           $twit_card_type= get_post_meta($post->ID,'cardtwitter_type',true);

       }

       if(has_excerpt()) {

           $twit_description= esc_attr(strip_tags(get_the_excerpt()));

       }

       elseif ($post->post_content !='') {

           $twit_description= esc_attr(strip_tags(wp_trim_words(do_shortcode($post->post_content), 21, '...')));

       }

       if(get_post_meta($post->ID,'cardtwitter_pic',true) != '') {

           $twit_pic= get_post_meta($post->ID,'cardtwitter_pic',true);

       } elseif (has_post_thumbnail()) {

           $twit_pic= wp_get_attachment_url(get_post_thumbnail_id($post->ID));

       } else {

           $twit_pic='ADD-A-DEFAULT-IMAGE-HERE';

       }

       ?><meta name="twitter:card" content="<?php echo $twit_card_type; ?>" />

<meta name="twitter:site" content="@ADD-YOUR-TWITTER-HANDLE" />

<meta name="twitter:title" content="<?php the_title_attribute(); ?>" />

<meta name="twitter:description" content="<?php echo $twit_description; ?>" />

<meta name="twitter:image" content="<?php echo $twit_pic; ?>" />

<meta name="twitter:url" content="<?php the_permalink(); ?>" /><?php

   }

}

add_action('wp_head','add_twitter_card_information');

[print-me-button buttontext="You can print a copy of this page for reference if required"]
Important Notes about the above code:

  1. change the ADD-A-DEFAULT-IMAGE-HERE to your preferred default image url.
  2. change the @ADD-YOUR-TWITTER-HANDLE to your Twitter handle.
  3. for the type of Twitter Card, the line "$twit_card_type='summary';" sets as default the Summary Card, however you may prefer to put in 'summary_large_image' or 'photo'. You can then choose which card to display for individual pages and posts using a custom field "cardtwitter_type" (referred to in the custom fields section below)
  4. for the page description this code first looks for an excerpt to use, otherwise it looks at the page content and outputs the first 21 words as the description (you can change that number to your preference). When using the page content, shortcodes will be executed to output the text so as not to see shortcodes output something like [heading title="title"...]. It also strips the tags and escapes the attribute so as not to cause errors with <, >, &, " and '.
  5. for the image this code looks first for an image in the custom field "cardtwitter_pic" (referred to in the custom fields section below), and if no image is found then it looks for a featured image. Lastly it will display your default image if nothing is found.


Using WordPress custom fields to choose Card Type and Image

WordPress posts and pages have support for custom fields. So we will create and use 2 custom fields when we want more control over the image for the Twitter Card and also when we want to select a Twitter Card other than the default we set in the function code.Let's go ahead and create that now. Go into a post or page editing screen. Click on "Screen Options" and make sure that "Custom Fields" is ticked.

custom fields in screen options

Now we enter the custom fields. Scroll down to the "Custom Fields" section and add a new custom field "cardtwitter_type", then either enter the text "summary", "summary_large_image" or "photo", depending on which type of card you want to display for that particular page or post. If you don't add the "cardtwitter_type" custom field to a page, then the default card type you have set in the function code will display. In a similar way, setting a custom field of "cardtwitter_pic" can be used to display a custom image for your Twitter Card, otherwise the featured image will display, or if none then the default image you have chosen will display.The short video below shows how easy it is to add the custom fields into your posts and pages.https://www.youtube.com/watch?v=NnS64dx59o4

Validating your Twitter Cards and testing them with Twitter's Validation Tool

Now that the markup is on your pages, you must be approved by Twitter before your cards will display. This is really easy. Go to Cards Validator and login to your Twitter account.Next enter in a url of a page you want to validate. When you click on the "Preview card" button, Twitter will then analyse that url for Twitter card markup, and if found it will display your card preview. It will also advise you what type of card markup it found and whether you are approved for that card. As in the image below, if you need to click on the "Request Approval" button then do so and fill in the form.

Request approval Twitter Summary Card

Twitter will display a message - if you are immediately rejected, then it may just be an issue at Twitter's end. Try requesting approval again. Make sure that there are no errors displaying. If you test the url again you should see a message that your approval is pending.

Pending card for Twitter

When approved, Twitter will send you an email to advise. You can also check using the Validator for the whitelisting message.

Whitelist Twitter Card

Very Important:Twitter requires you to request approval for each of the card types. So choose a url for each Twitter Card type, and "Request Approval" for each.So that's how you setup Twitter Cards for Summary Cards, Summary Cards with Large Image, and Photo Cards for your WordPress website.[print-me-button]

Comments: