Add Twitter Card to WordPress without Plugin

Reading this blog, one may think I focus on WordPress development and enhancements. That is not the case by any means. The focus of my career focused on the implementation of Microsoft Dynamics 365 Business Central. The concept behind this blog is to share bits of [technical] “stuff” that I encounter on my journey. The WordPress concepts come into play as I continue to enhance this site.

Sharing the content on this site on social platforms is another way to relay information that may be helpful to some. I recently became more active in the following Twitter posts and felt that it would be an excellent platform to share my blog posts. 

I went over to Twitter, pasted the link to a blog post that I wanted to share, and hoped to see a “preview” of the content. Well, I was wrong. The only thing in the “tweet” was the link to the post. After a bit of digging, I found that there is a “Twitter Card.” The Twitter Card is meta-information on the page of your site that relays to Twitter how the page preview should look in a Tweet. I found that there is a Twitter Card Validator that will alert you of any Twitter Card issues for the link that you’d like to Tweet. Of course, my post failed validation.

Several WordPress Plugins are available that add Twitter Cards to your pages, but I prefer to use as few Plugins as possible to reduce the risk of any issues. Just as I did when changing the Login Page, I opted to get the Cards onto my posts myself through functions and actions.

Add the following to your Theme’s functions.php file (replace the image url and the twitter creator tag with your image and tag):

function twittercard()
{
	if(is_single() || is_page()) {
    	$twitter_title  = get_the_title();
		$twitter_url    = get_permalink();
		$twitter_desc   = get_the_excerpt();
		$twitter_image	= 'https://www.dvlprlife.com/tweetimage.jpg?rating=PG&size=75';
		
		echo '<meta name="twitter:card" value="summary" />';		
		echo '<meta name="twitter:title" value="'  . $twitter_title . '" />';
		echo '<meta name="twitter:url" value="' . $twitter_url . '" />';
		echo '<meta name="twitter:description" value="' . $twitter_desc . '" />';
		echo '<meta name="twitter:image" value="' . $twitter_image . '" />';

		echo '<meta name="twitter:creator" value="@dvlprlife" />';
	}
}

add_action('wp_head', 'twittercard');

 

Please note that doing this without a plugin does require some programming knowledge, and before ever making any changes, you should always back up your site.

Make a note and save the code added; if the function.php file is updated and replaced, the code will need to be added to the file again. You can also look into setting child themes to keep you from losing the edit.

Leave a Reply

Your email address will not be published.