X

Crie um widget personalizado do Twitter sem um plug-in

Já me perguntaram algumas vezes sobre qual plug-in do WordPress eu uso para gerar a lista “Twitter Feed” no rodapé do meu site. Na verdade, não uso nenhum plug-in, é um trecho de Javascript do Twitter que exibe uma lista dos meus tweets recentes que estilizei com CSS. Neste tutorial, mostrarei a você:

  • O código HTML e Javascript necessário para extrair os tweets mais recentes
  • Uma visão geral da marcação HTML e dos seletores CSS associados
  • Dois exemplos de widgets do Twitter com estilo personalizado que eu mesmo usei

Continue lendo para ver o restante do tutorial…

O HTML e o Javascript

O Twitter costumava fornecer esse código em seu site, mas por algum motivo o removeu em favor desses widgets muito menos flexíveis. Você precisará de dois trechos de código.

Primeiro, coloque o código a seguir onde você deseja que a lista seja exibida:

<ul id="twitter_update_list"><li>Carregamento do feed do Twitter</li></ul>

Observação: O <li>carregamento do feed do Twitter</li> não faz parte do código original fornecido pelo Twitter, mas é necessário para que o HTML seja validado. Ele também pode fornecer uma mensagem útil enquanto o feed está sendo carregado, pois pode levar alguns segundos em um dia lento.

Em segundo lugar, você precisará colocar as seguintes linhas de Javascript o mais próximo possível da tag </body>.

<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/USERNAME.json?callback=twitterCallback2&count=3"></script>

No momento, eu o coloco logo acima do meu código do Google Analytics.  Você deve manter essas linhas de Javascript o mais baixo possível na página porque, caso o Twitter não carregue, tudo abaixo desse código ficará suspenso (o que não é um grande problema se já estiver na parte inferior).

Visão geral da marcação HTML e dos seletores CSS

Agora você não pode ver a marcação HTML gerada pelo widget do Twitter sem usar algo como o Web Developer Toolbar. Para sua sorte, eu fiz isso para você. Aqui está uma lista de amostra com apenas um tweet como exemplo.

<ul id="twitter_update_list">
<li><span>RT @<a href="http://twitter.com/Screenr">Screenr</a>: Atualização legal do Screenr: agora seus screencasts são publicados duas vezes mais rápido. <a href="http://screenr.com/aDp">http://screenr.com/aDp</a></span> <a style="font-size: 85%;" href="http://twitter.com/themelab/statuses/14229492866">46 minutes ago</a></li>
</ul>
  • #twitter_update_list – Seleciona a lista inteira
  • #twitter_update_list li – Seleciona itens individuais da lista
  • #twitter_update_list li span – Seleciona a parte “tweet” do item da lista, não o link de tempo atrás
  • #twitter_update_list li span a – Seleciona o link dentro da parte “tweet” do item da lista
  • #twitter_update_list a[style="font-size: 85%;"] – Seleciona o link "time ago", de uma forma um tanto hacker (veja a nota abaixo).

Observação: Como há um estilo embutido no link time ago que define o tamanho da fonte em 85%, é um pouco difícil substituí-lo sem um código complicado. Já usei isso antes para redefinir o tamanho da fonte para o mesmo que o restante da lista:

#twitter_update_list a[style="font-size: 85%;"] { font-size: 1em !important; }

Isso provavelmente não funciona nas primeiras versões do IE por causa da parte “!important”. Você também pode usar display: block; para mover esse link para a próxima linha.

Exemplo ao vivo

Para ver um exemplo ao vivo, dê uma olhada no rodapé do Theme Lab. Ou, se estiver lendo isto em seu leitor de feeds ou em um site de scraper não autorizado, veja a captura de tela abaixo.

Theme Lab Twitter Feed

Aqui está o código que uso para a lista:

#twitter_update_list {
	tamanho da fonte: 13px;
	altura da linha: 21px;
	list-style: none;
	}
#twitter_update_list li {
	background: url('images/twitter-divider.gif') bottom left repeat-x;
	padding-bottom: 7px;
	margin-bottom: 9px;
	}
#twitter_update_list span, #twitter_update_list span a {
	color: #ababab;
	decoração de texto: nenhum;
	}
#twitter_update_list a {
	color: #6f7276;
	}
  • A primeira linha seleciona a lista inteira. Ela define o tamanho da fonte, a altura da linha e garante que nenhum marcador apareça.
  • A segunda linha faz com que uma pequena imagem 2×1 se repita abaixo de cada item da lista como uma espécie de divisor. O preenchimento define o espaço entre o tweet e a borda superior do divisor. A margem define o espaço entre a borda inferior do divisor e o próximo tweet.
  • A terceira linha define a cor do tweet, incluindo os links, e garante que nenhuma linha apareça abaixo dos links.
  • A última linha define a cor do link “time ago”.

E é isso! Se eu tivesse que mudar alguma coisa, eu diferenciaria os links no tweet de alguma forma e talvez adicionasse efeitos de foco nos links também.

Isso pode ser usado em qualquer site

Ao contrário de todas as outras postagens sobre como fazer XYZ sem um plug-in, não há nenhum código real do WordPress usado neste tutorial.

Como ele não usa código do WordPress, não está arquivado na coleção Tutoriais do WordPress. Ele pode ser usado em praticamente qualquer tipo de site, desde que você saiba editar código-fonte HTML e CSS.

Se quiser usá-lo no WordPress, sugiro editar manualmente os arquivos de tema para inserir as duas linhas de Javascript no rodapé do site ou até mesmo conectá-lo ao gancho wp_footer().

Quanto ao widget em si, você pode colar o código dentro de um widget de texto ou codificá-lo manualmente na barra lateral (ou onde quer que seja).

Conclusão

Espero que tenham gostado do tutorial e gostaria de ouvir suas opiniões nos comentários. Se você tiver alguma solicitação de dicas rápidas sobre WordPress ou CSS, sinta-se à vontade para me informar. Ele poderá ser apresentado em uma futura postagem do Tutorial Tuesday no Theme Lab!

Comentários   Deixe uma resposta

  1. Just wanted to note that the 2nd line of code of Javascript no longer works. For anyone implementing this, please make sure you replace the 2nd line of code with the following:

    Leland, you may want to update your post to reflect this.

    1. Rich – looks like your code disappeared… can you try to post with some spaces please???

      Thanks

  2. Looks like this is no longer working. Any ideas?

  3. Dear Leland,

    Do know why the twitter feed app which you posted on your website is not functioning anymore. even on your own website is doesn’t work.

    I hope to hear from you.

    Most kind regards,

    André van Wijngaarden

    1. Twitter basically changed the url for their feeds. Granted everything else was still working, I had assumed this might’ve been the case.

      ——
      Instead of using the URL provided in the tutorial above: http://twitter.com/statuses/user_timeline/USERNAME.json?callback=twitterCallback2&count=3

      …You will want to use the URL I’m proving that follows:
      http://api.twitter.com/1/statuses/user_timeline.json?screen_name=USERNAME&include_rts=true&count=3&callback=twitterCallback2

      The “count” is now located in the midst of the url instead of at the end, along with the username.

      Enjoy.
      <3 ~ CaT

  4. my comment is still awaiting moderation, but I’ve found the solution on the twitter developers site.

    https://dev.twitter.com/discussions/11701

    change this:

    to this:

  5. This method no longer works?

    I see it’s also giving this website the same issue in your footer widget.

    Any updates?

  6. Caroline McQueen outubro 22, 2012 em 5:05 am

    For some reason this has stopped working on my blog. Any ideas why?

    I had to switch to a jquery widget for the rest of my site but that doesn’t work in wordpress 🙁

  7. Does this still work? I only have the “twitter feed loading” bit coming up. If not, have you got another way?

  8. I was using this method on a few client sites. It recently broke across the board. looks like it’s not working in the footer here (themelab.com) as well.

    Ahhh! Anyone have a solution?

  9. The API call “http://twitter.com/statuses/user_timeline/USERNAME.json?” used here has been deprecated, so replace it with the following:

    https://api.twitter.com/1/statuses/user_timeline.json?screen_name=USERNAME&count=2&callback=twitterCallback2

  10. Is there anyway to make the list completely horizontal?
    So that all three tweets display in a row rather than stacked on top of each other?
    (I’m using it as a marquee)
    I want the first tweet to scroll across, then the 2nd tweet..and so on.

    Rather than all 3 displaying at one time.

  11. Sorry to resurrect such an old post, I have implemented your code and it works great for IE9, but will not load for FF 14. I have had similar issues with twitter plugins, too. Chrome, blackberrry all work fine and load. Could it be an issue with my CSS and something else that is causing it to hang in FF?

  12. For the sake of other n00bs like me: replace USERNAME in the above code with your actual Twitter username. 😉

    Thanks for this!

  13. You can also target the time stamp link with a pseudo class:
    #twitter_update_list a:last-child

  14. Brilliant tutorial. Thank you.

    Can you tell me how to get the ago link to sit bottom right away from the text as you have on your website.

    Many Thanks

  15. If there’s someone interested in the translation to other languages of the “time ago” link I tell you that I just downloaded the blogger.js, modified it and it works.

    You Just have to translate the captions, don’t mess with the code, here’s an example.

    if (delta < 60) {
    return 'hace menos de un minuto';
    } else if(delta < 120) {
    return 'hace aproximadamente un minuto';
    } else if(delta < (60*60)) {
    return 'hace ' + (parseInt(delta / 60)).toString() + ' minutos';
    } else if(delta < (120*60)) {
    return 'hace aproximadamente una hora';
    } else if(delta < (24*60*60)) {
    return 'hace ' + (parseInt(delta / 3600)).toString() + ' horas';
    } else if(delta < (48*60*60)) {
    return 'hace un dia';
    } else {
    return 'hace ' + (parseInt(delta / 86400)).toString() + ' dias';
    }

    By the way, thanks a lot for the tutorial, it helped me a lot.

  16. Hi Leland,

    Thanks for your script! Almost got it working like i want it to…Any chance of fixing the size of the list? I want to generate the list inside a cell, but when the tweets exceed the cell, the cell explodes!

  17. Fantastic, but I’m not getting a result (.js newbie). My site (callumflack.com) just renders “twitter feed loading” w/o actually pulling thru the twitter feed. I’ve double-checked everything in this post, but no dice. What have I missed? Your help greatly appreciated.

  18. thanks for this 🙂 you can change the links within the tweets using ‘#twitter_update list span’, then the time of the tweets using ‘#twitter_update list span a’. also, using last-child removes the horizontal line from below the last tweet. see below for my code.

    #twitter_update_list {
    font-size: 10px;
    line-height: 15px;
    list-style: none;
    }

    #twitter_update_list li {
    background: url(‘images/1px-grey.gif’) bottom left repeat-x;
    padding-bottom: 10px;
    margin-bottom: 10px;
    }

    #twitter_update_list li:last-child {
    background: none;
    }

    #twitter_update_list span {
    color: #856f6a;
    text-decoration: none;
    display: inline;
    }

    #twitter_update_list span a {
    color: #fb3898;
    display: inline;
    }

    #twitter_update_list a {
    color: #b3a39f;
    display: block;
    }

  19. Thanks for this. For those that asked…

    You can change this to a list by changing the first part of the URL in the second script from:

    http://twitter.com/statuses/user_timeline/USERNAME.json?

    to

    http://api.twitter.com/1/USERNAME/lists/LISTNAME/statuses.json?

  20. Hi,

    Good tutorial. However my site started showing 3 tweets, now its very speradic and sometimees decides to show 2 or 1.

    Am I being dim here?

    Rob

    1. That’s a good question. I’ve noticed when you retweet (as in official Twitter-style retweet) something, it doesn’t show up, and instead just shows one less tweet.

  21. I strongly dislike the way the official Twitter feeds look, so I was happy to find your site. The tutorial was very informative and easy to follow, and I cannot wait to incorporate this into my website redesign.

  22. Great article.

    Just had to amend the & top &amp; so the HTML validated.

    Nice work!

  23. I know this was posted a while ago, but is there a way to separate the most recent tweet from the previous tweets so you can put a label on them like “Latest Tweet” and “Older Tweets”?

  24. Love this! Is there a way to force links within each tweet to open in a new window?

Adicionar um comentário

Ficamos felizes por você ter optado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossa política de privacidade, e todos os links são nofollow. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.

WordPress Launch Checklist

A lista de verificação definitiva para o lançamento do WordPress

Compilamos todos os itens essenciais da lista de verificação para o lançamento de seu próximo site WordPress em um ebook prático.
Sim, envie-me o livro eletrônico gratuito grátis!