Show Image on Twitter WordPress Cards without plugin

0

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');
    
asked by anonymous 09.04.2017 / 16:50

1 answer

1

You should create an auxiliary function to pull the highlighted image or any missing image associated with the specific post. All failing, put a default image of the site.

Here, check if the post has the image highlighted and if it does it wp_get_attachment_... :

$featured = has_post_thumbnail( $post->ID );

If you do not have it, pull all the images in the post, or just 1:

$args = array(
    'post_type'   => 'attachment',
    'numberposts' => -1, // todas as imagens, trocar pra 1 se quiser só uma
    'post_mime_type' => 'image',
    'post_parent' => $post->ID
);

$attachments = get_posts( $args );
// puxar as informações do attachment usando o post->ID dela

PS: Code type is very easy and simple to use as a plugin. So, Twitter Card will work when you change Theme without having to be copying / pasting functions.php . You can also use the plugin on other websites easily.

    
05.05.2017 / 00:29