I have this code, to add Twitter Cards without the need of 1 plugin, just adding the code in functions.php.
The code works, but the article image only appears if you have attached it to the post.
I would like to change it to show the 1 independent article image if it is attached.
function my_twitter_cards() {
if (is_singular()) {
global $post;
$twitter_user = str_replace('@', '', get_the_author_meta('twitter'));
$twitter_url = get_permalink();
$twitter_title = get_the_title();
$twitter_excerpt = get_the_excerpt();
$twittercard_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
$twittercard_thumb = $twittercard_image[0];
if (!$twittercard_thumb) {
$twittercard_thumb = 'http://www.example.com/default-image.png';
}
if ($twitter_user) {
echo '<meta name="twitter:creator" value="@' . esc_attr($twitter_user) . '" />' . "\n";
}
echo '<meta name="twitter:card" value="summary" />' . "\n";
echo '<meta name="twitter:url" value="' . esc_url($twitter_url) . '" />' . "\n";
echo '<meta name="twitter:title" value="' . esc_attr($twitter_title) . '" />' . "\n";
echo '<meta name="twitter:description" value="' . esc_attr($twitter_excerpt) . '" />' . "\n";
echo '<meta name="twitter:image" value="' . esc_url($twittercard_thumb) . '" />' . "\n";
echo '<meta name="twitter:site" value="@mhthemes" />' . "\n";
}
}
add_action('wp_head', 'my_twitter_cards');