I want to share with you how you can conditionally make Twitter Cards for your WordPress website.
Conditional Twitter Card Code for Your Website’s Head
Have you ever shared a link to your website on Twitter and a blank — or broken — image displays? I’ve been there, too.
Solve the issue by adding a little snippet of code to your WordPress website’s header.php
PHP file.
Start with the optimized Twitter Card code from Twitter’s developer tools. Then sprinkle in a touch of WordPress allowing text and images to load dynamically. And, use conditionals to load it on the pages you want (or everywhere).
Get the Code
Here’s a snippet for your Twitter cards. Copy and paste it into your WordPress site’s head section: <head>[CODE GOES HERE]</head>
. Make sure to fill in your own information.
<!-- Twitter Card Info --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@FloydHartford"> <meta name="twitter:creator" content="@FloydHartford"> <?php if (is_front_page()) : ?> <meta name="twitter:title" content="Your Headline Text"> <meta name="twitter:description" content="Enter a short description of your content"> <meta name="twitter:image" content="http://www.yoursite.com/the-path-to-your/image.jpg"> <?php else: ?> <meta name="twitter:title" content="<?php the_title(); ?>"> <meta name="twitter:description" content="<?php the_excerpt(); ?>"> <meta name="twitter:image" content="<?php the_post_thumbnail_url(); ?>"> <?php endif; ?> <!-- End Twitter Card Info -->
As far as conditionals, WordPress has many different conditional tags you can choose from. Some of my favorites are is_front_page()
, is_home()
, is_page()
, and is_single()
. These would respectfully run the code on your website’s home page, blog page, normal page, and single post pages and can be combined to load the code on a combination of pages, as well.
Automate Twitter Cards with Yoast SEO for WordPress
Another way to add Twitter Cards to your WordPress website is through the Yoast SEO Plugin. Yoast SEO lets you automate Twitter cards on the fly by using a post or page’s featured image and adding the Twitter Card code to your WordPress site for you. This way, you don’t need to edit the WordPress theme or template files yourself.
0 Comments