Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Guia para iniciantes sobre como adicionar cartões do Twitter no WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Deseja adicionar Twitter Cards ao seu site WordPress? Os Twitter Cards são imagens e descrições que aparecem no Twitter quando alguém compartilha seu conteúdo.

Ele ajuda a controlar a aparência dos seus tweets no Twitter, a obter crédito ao incluir automaticamente o seu nome no tweet e a aumentar o envolvimento do usuário.

Neste artigo, mostraremos como adicionar Twitter Cards no WordPress, para que seus tweets se destaquem.

Beginners Guide on How to Add Twitter Cards in WordPress

Por que usar Twitter Cards no WordPress?

Os Twitter Cards permitem que você adicione um título, um resumo, uma imagem e um arquivo de vídeo ou áudio ao seu tweet. Dessa forma, é mais provável que você receba mais cliques e retweets.

Você pode ver um exemplo ao vivo acessando nossa página no Twitter.

twitter card example

A maior vantagem de ter Twitter Cards é que eles aumentam o número de pessoas que seguem suas contas no Twitter por meio da atribuição de conteúdo. Muitas vezes, as pessoas tuitam seus links sem lhe dar o devido crédito.

Por exemplo, digamos que @syedbalkhi retuite uma publicação de @wpbeginner sem atribuição, e outras pessoas retuitem @syedbalkhi. Então, os usuários que visualizam esses retuítes têm mais probabilidade de seguir @syedbalkhi do que @wpbeginner.

Muitas vezes, os curadores de conteúdo fazem isso para manter a duração dos tweets curta e garantir retweets de seus próprios tweets.

Com os Twitter Cards, esse problema é resolvido porque você recebe crédito para o seu site WordPress de cada tweet que menciona seu artigo.

Agora que você conhece os benefícios dos Twitter Cards, vamos dar uma olhada em como implementá-los no WordPress. Abordaremos dois métodos e mostraremos como testar e validar seus Twitter Cards:

Método 1: Usar o plug-in AIOSEO para adicionar cartões do Twitter (recomendado)

A maneira mais fácil de adicionar Twitter Cards ao seu site é usar o plug-in All in One SEO (AIOSEO) para WordPress. Ele é o melhor plug-in de SEO para WordPress e é usado por mais de 3 milhões de sites.

Primeiro, você precisará instalar e ativar o plug-in AIOSEO. Para obter mais detalhes, siga nosso tutorial passo a passo sobre como instalar um plug-in do WordPress.

Você pode usar a versão gratuita do AIOSEO, pois ele oferece um recurso para configurar Twitter Cards em seu site WordPress.

Depois que o plug-in estiver ativo, vá para a área de administração do WordPress e navegue até All in One SEO ” Social Networks. Em seguida, clique na guia “Twitter” e certifique-se de que a opção “Enable Twitter Card” esteja ativada.

enable twitter card option

Depois de ativar os Twitter Cards, você pode alterar sua aparência usando diferentes configurações.

O AIOSEO permite que você selecione o tipo de cartão padrão para o seu conteúdo. O plug-in definirá “Summary” (Resumo) como o tipo de cartão padrão, que mostra o título, o resumo e a imagem em miniatura do seu conteúdo.

No entanto, você pode alterá-lo para “Resumo com imagem grande” no menu suspenso, e o Twitter mostrará seu tweet com uma imagem grande.

default card type

Depois disso, você precisa selecionar a Default Post Image Source. Essa é a imagem que você deseja exibir em seus Twitter Cards.

Há diferentes opções para escolher usando o menu suspenso. Por exemplo, você pode carregar ou selecionar uma imagem padrão que aparecerá no Twitter Card ou selecionar a imagem em destaque, a imagem anexada, a primeira imagem no conteúdo e muito mais.

select default post image source

Em seguida, adicione uma Default Post Twitter Image, que será usada como backup caso seu conteúdo não tenha uma imagem.

Por exemplo, se a origem da imagem da postagem for uma imagem em destaque, mas a postagem não tiver uma imagem em destaque, o Twitter usará a imagem padrão.

upload default post twitter image

Além disso, o AIOSEO oferece mais opções para mostrar dados adicionais, como o autor da postagem e o tempo necessário para ler um artigo.

Há também uma opção para definir a fonte de imagem do termo padrão, mas você precisará do AIOSEO Pro ou de uma licença superior para usar esse recurso.

Agora, se você rolar a tela para baixo, verá as configurações da página inicial do Twitter. O plug-in mostrará uma prévia de como sua página inicial será exibida em um cartão do Twitter.

home page settings

Nessa seção, é possível alterar o tipo de cartão e adicionar uma imagem da página inicial.

Isso é semelhante às etapas que mostramos anteriormente, mas a diferença é que essas configurações são para sua página inicial.

home page card type and image

Em seguida, insira um título e uma descrição da Home Page que serão exibidos no cartão do Twitter.

Feito isso, clique no botão “Save Changes” (Salvar alterações).

home page title and description

Além disso, o AIOSEO também permite que você altere as configurações do Twitter Card para publicações e páginas individuais.

Para fazer isso, edite qualquer post ou página do blog e role para baixo até as Configurações do AIOSEO no editor de conteúdo. Agora, clique na guia “Social” e selecione “Twitter”.

aioseo settings

O plug-in mostrará uma visualização do cartão do Twitter do seu post e lhe dará a opção de usar os dados da guia Facebook. Ele também permite que você edite o título e a descrição do Twitter.

Você pode escrever um novo título e uma nova descrição ou usar tags inteligentes. Por exemplo, se você usar a tag “+ Título da postagem” acima do campo Título do Twitter, o AIOSEO usará automaticamente o título da sua postagem no cartão do Twitter.

twitter card settings for posts and pages

Depois disso, role para baixo e selecione a Fonte da imagem para seu cartão do Twitter. Use o menu suspenso para selecionar a imagem que deseja exibir em sua postagem, como uma imagem em destaque, uma imagem anexada, a primeira imagem no conteúdo e assim por diante.

Por fim, você pode selecionar o tipo de cartão do Twitter no menu suspenso. Por padrão, o AIOSEO o definirá como “Resumo”, mas você pode alterá-lo para “Resumo com imagem grande”.

image source and card type

Em seguida, atualize ou publique sua postagem no blog. Agora você adicionou com êxito os Twitter Cards ao seu site WordPress.

Método 2: Adicionar cartões do Twitter no WordPress (método de código)

Esse método requer a adição de código aos arquivos de seu tema ou tema filho. Basta abrir o arquivo header.php ou usar o plug-in gratuito WPCode para adicionar esse código personalizado logo antes da tag </head>:

<?php
#twitter cards hack
if(is_single() || is_page()) {
  $twitter_url    = get_permalink();
 $twitter_title  = get_the_title();
 $twitter_desc   = get_the_excerpt();
   $twitter_thumbs = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), full );
    $twitter_thumb  = $twitter_thumbs[0];
      if(!$twitter_thumb) {
      $twitter_thumb = 'http://www.gravatar.com/avatar/8eb9ee80d39f13cbbad56da88ef3a6ee?rating=PG&size=75';
    }
  $twitter_name   = str_replace('@', '', get_the_author_meta('twitter'));
?>
<meta name="twitter:card" value="summary" />
<meta name="twitter:url" value="<?php echo $twitter_url; ?>" />
<meta name="twitter:title" value="<?php echo $twitter_title; ?>" />
<meta name="twitter:description" value="<?php echo $twitter_desc; ?>" />
<meta name="twitter:image" value="<?php echo $twitter_thumb; ?>" />
<meta name="twitter:site" value="@libdemvoice" />
<?
  if($twitter_name) {
?>
<meta name="twitter:creator" value="@<?php echo $twitter_name; ?>" />
<?
  }
}
?>

Você pode alterar o valor ‘twitter:card’ na Linha 14 para ‘summary_large_image’ se quiser exibir um cartão de resumo com uma imagem grande.

Se você não souber como trabalhar com PHP ou tiver problemas com o Método 2, use o Método 1.

Teste e valide seus cartões do Twitter

Antes que os links do seu site WordPress comecem a exibir os cartões do Twitter, você precisa primeiro verificá-los no validador de cartões do Twitter.

Basta acessar a página do Card Validator no site dos desenvolvedores do Twitter. Digite o URL de qualquer post de seu site WordPress e clique no botão “Preview card” (Visualizar cartão).

Twitter Card Validator

O validador de cartão não exibe mais uma visualização do tweet, mas mostra um registro se o cartão do Twitter foi carregado com sucesso ou não.

Atualização: Anteriormente, era necessário solicitar a participação nos Twitter Cards. No entanto, o Twitter implementou um sistema que automaticamente coloca os domínios na lista branca quando você os testa com o validador ou simplesmente compartilha um URL no Twitter.

Guias especializados sobre como usar o Twitter com o WordPress

Agora que você sabe como adicionar cartões do Twitter ao WordPress, talvez queira ver outros guias relacionados ao uso do Twitter com o WordPress.

Esperamos que este artigo tenha ajudado você a adicionar cartões do Twitter ao WordPress. Talvez você também queira ver nosso guia sobre como criar uma página de destino com o WordPress e nossa seleção de especialistas dos plug-ins obrigatórios do WordPress para expandir seu site.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

88 ComentáriosDeixe uma resposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Aramide says

    You’ve been so awesome in passing great information on WordPress. Your tutorials are so great and are wonderful learning materials. Thanks for always being there for us.

  3. Dee says

    Hi! I have a free wordpress.com blog, and I’m not sure how to add twitter cards to that. I don’t know if I can edit the html of my theme without a plugin (if I can, I don’t know how to find the html code) (super new to WP) is there any way to add twitter cards for free

  4. MStokely says

    Thank you! It took awhile for this to work I guess because cache needed to be cleared but this is the ONLY solution I found that worked.

  5. Pierre says

    Question about this, when I am posting a link from my site on Twitter, the preview image is only showing the WordPress W logo instead of what I set in Yoast. Is it just a matter of waiting it out or a, I doing something wrong?

    • WPBeginner Support says

      You may want to ensure you’ve cleared any caching on your site for twitter to get the correct image and after that, you would need to wait for Twitter’s cache to clear.

      Administrador

  6. MIke says

    Hey there, very late to this article but am wondering how to amend the php code to produce the large image with summary card.

    I’ve given it a shot but not managed it yet. Ideas and advice appreciated.

    cheers

  7. Mark Larson says

    I’m getting this error:

    “Notice: Use of undefined constant full – assumed ‘full’ in”

    Not sure how to get rid of it.

  8. Ted Bergman says

    Thanks for this post. When I need to know how to do something on WordPress I come here first. Your easy to understand instructions are priceless!

  9. Sarah Bridge says

    I’ve done all the steps using Yoast and validated my url – but there is still no image coming up when I post my URL on Twitter? It said this:

    Sarah Bridge
    The card for your website will look a little something like this!

    and underneath on the right hand side it has the correct words but on the left hand side where an image should be there’s nothing but a grey box with what looks like a grey scroll in it. You can click on it to get to my website but I’d like a image there rather than a grey box. Any thoughts?

  10. Daniela says

    Have successfully done this in the past. However, it was always when using summary card with large image (which is set as the default in my Yoast settings). Now trying to post summary card (regular, not large image), but Yoast is overriding it to summary card large image. How do I prevent this?

    As a note, I’m doing both methods: adding info to Yoast plug in and writing metadata tags in a plug in.

  11. Nick Farrell says

    You can also just throw your meta tags right into the body of your post. Not the ideal way, since this creates empty white space where your tags are, but it’s a good workaround for those having trouble.

  12. Laurel says

    If the php code above seems to break your site, it could be that your server doesn’t use php short tags (using “<?" as an opening tag instead of "<?php"). Try this version instead:

  13. Prabs says

    Hi thanks for the informative post. However I did all this and when testing my site through the card validator, was told it was unable to generate image because my site isn’t whitelisted! Any idea what I can do?

  14. Sarah says

    Hi,

    I realise this is an old post,

    IF you HARDCODE into your header.php; make sure you change the values line 10 and 19 as these point to the contributors account so be sure to change them to yours.

    just sayin … ;-)

  15. Jahmya says

    Hi,
    I have done all the steps when I try to validate with twitter it tells me my text description meta tag is missing. I don’t know anything about code so I used the first method. Any help?

  16. Tyler says

    Finally a helpful tutorial! You would think that Twitter would make it a little simpler to do this. Thank you so much for your help on this!

  17. Michael says

    Is there a way to automatically notify the twitter validator when a post/page is updated?

    I have a site that gets content published automatically from a source without a featured image so once I manually add the image I also have to manually validate the post/page again to get the cards to show on twitter.

    Was hoping there could be some way to automatically ping the twitter validator when a page/post is updated.

  18. Azita says

    I don’t know why the code above cut off.
    Here is the code am using:
    ID), full );
    $twitter_thumb = $twitter_thumbs[0];
    if(!$twitter_thumb) {
    $twitter_thumb = ‘url of imag’;
    }
    $twitter_name = str_replace(‘@’, ”, get_the_author_meta(‘twitter’));
    ?>
    <meta name="twitter:title" content="” />
    <meta name="twitter:description" contente="” />
    <meta name="twitter:image" content="” />

  19. Adrian Robertson says

    Another awesome post … great stuff!

    For anyone having issues with the image being display (I have Summary selected as my Twitter Card option) just make sure you are using a featured image, as this is where it pulls from.

    Without this specified, what I saw was my site logo (which was way too big for the Summary image)

  20. shamsher says

    i have a question that when where to upload it on all pages and post or on home page only.

    bcoz when i share any link of my blog on twitter after adding this in header every time same image appears.

    • Adrian Robertson says

      Is it your site logo that appears?
      Just check that you have a feature image set against your post, and it should pull from there

  21. Roger Dunkelbarger says

    Found this article and followed the steps to set up Twitter Cards since we already had Yoast. We want to use the video Player Card but that doesn’t appear to be an option. Do we need to use a different plug in, or is that option available?

  22. Amanda says

    I”m using twitter cards through my Yoast SEO, however when I post I have a link and a view summary button that people have to click to see my pictures. I want the pictures to be auto populated without the need for a click. How do I make that happen?

    Here is my twitter account so you can see my tweets for an example

  23. Graham says

    All going well with the inclusion of twitter cards. I would like to make the image that displays on twitter link able or to a link underneath to take it to a third part site any ideas?
    Oh and by the way I would like to thank you guys for realizing that not everyone degree is in computer science and won at MIT !!

  24. Jas says

    Hi,

    Thanks for your tutorial. I have tried with above code. But can you please explain how to make Twitter card working for multiple accounts.

    I have ten different twitter pages where same post will go out as Twitter card.

    So do I need to repeat this below line 10 times with different names:

    …..

    ….
    ….

    Please suggest?

    Thanks!

    • jas says

      code doesn’t shows in my previous comment I mean to say meta tag with Twitter site name need to get repeated with different names?

      <meta name="twitter:creator" value="@” />

  25. Edna says

    This was super helpful, thanks!

    One quick thing, I noticed the validation link is no longer working. I think this is the Card Validator link now (got it from the twitter blog, seemed to work fine for me):

  26. Maha says

    How to request to twitter for approvel my site ..please help me i tried twitter card ,the preview tool say your card is whitelisted ..

  27. riad says

    hi i love your site very nice i want to asking you how to change the language of wordpress from franch to english or arabic

  28. samiOOTB says

    I had done this and Twitter cards were working perfectly for months. Suddenly the past few days they’ve stopped working. What can I do?

  29. Megan Kubasch says

    So I have installed WP SEO by Yoast, and I have followed all of the instructions up to the point where I insert the Card URL on the Preview page for the Card Validator on Twitter. What URL am I supposed to Insert? I have used my URL for my blog, but it comes up with an error, saying No Card Found (Card Error). Any help you can provide would be greatly appreciated.

  30. Lauren Riley says

    This is really useful thank you.

    One thing, we have enabled this using the WordPress Yoast SEO Plug-in and set up a Twitter card manually entering all of the information on the card validator for one blog post.

    This worked, however when I tweet a link to my other blog posts it doesn’t pull through the Twitter card. Do you have to set up the Twitter cards for each blog post or should it do it automatically for each blog post?

  31. Ruth says

    Oh, and ps
    Do we have to approve each post, or will that be automatic after our first post was approved… Again, thank you

  32. Karan Singh says

    when i install this plugin then it is asking for “You’ve just installed WordPress SEO by Yoast. Please helps us improve it by allowing us to gather anonymous usage stats so we know which configurations, plugins and themes to test with” Allow Tracking or not, what should i do,
    Allow tracking or not.

  33. Kevin says

    Hello there. Great guide, thanks!

    I’m currently stuck trying to validate twitter:creator. When I look at the source for one of my posts, I don’t see the twitter:creator meta tag at all. Would you mind, pointing me in the right direction? I’m hard-coding it.

  34. Gareth says

    Great post – i was struggling to set up twitter cards using a wordpress plug in without realising that Yoast had it in-built!

    All set up and awaiting approval – thanks guys

  35. Jason Acidre says

    Useful post! Been planning to add Twitter cards on my blog for ages now, and just had the time to tweak it earlier, found this guide very helpful, so thanks.

  36. Julien Maury says

    Hi,

    It’s great but because we call the excerpt outside the loop (header), people could get bad surprises for their description.

    So here is a good snippet from uplifted.net that fixes the problem :

    function get_excerpt_by_id($post_id){
    $the_post = get_post($post_id); //Gets post ID
    $the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
    $excerpt_length = 35; //Sets excerpt length by word count
    $the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
    $words = explode(‘ ‘, $the_excerpt, $excerpt_length + 1);
    if(count($words) > $excerpt_length) :
    array_pop($words);
    array_push($words, ‘…’);
    $the_excerpt = implode(‘ ‘, $words);
    endif;
    $the_excerpt = ” . $the_excerpt . ”;
    return $the_excerpt;
    }

    Then you might replace get_the_excerpt() with this :
    get_excerpt_by_id($post_id)

    Thanks. :)

  37. Manuel Garcia says

    When I preview my twitter card, the error says:
    “Internal Error. Most likely an fetcher error.”
    What to do?

  38. Sai Liou says

    Thank you for the article! I went with method #1. In the twitter preview, I’m only seeing the summary of the post and not the image. I’ve updated the robot.txt file to allow twitterbot. However, it’s still not showing any image in the preview. Any thoughts on this? Thank you in advance.

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.