Display image on Twitter Wordpress Cards without plugin

Asked

Viewed 87 times

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 image of the article only appears if attached to the post.

I would like to change it to show the 1 image of the independent article 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');
  • How the code should know which image to use if it is not attached to the post?

1 answer

1

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

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

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

If not, pull all post images, or only 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: is the type of code very easy and simple to use as plugin. So, Twitter Card will work when you change your Theme without having to copy/paste from functions.php. You can also use the plugin on other sites easily.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.