Volete visualizzare il numero di follower di Twitter come testo in WordPress?
Mostrando che molte persone vi seguono sui social media, potete incoraggiare i visitatori a fidarsi del vostro sito web. Inoltre, visualizzando queste informazioni come testo, avrete la libertà di utilizzarle in qualsiasi punto del vostro sito, anche all’interno di post e pagine.
In questo articolo mostreremo come visualizzare il conteggio dei follower di Twitter come testo in WordPress.
Perché visualizzare i follower di Twitter come testo in WordPress?
Avrete notato che molti blog, influencer e marchi famosi mostrano con orgoglio quante persone li seguono sui social media.
Se i visitatori vedono molte persone che vi seguono sui social media, è più probabile che si fidino della vostra attività e vi considerino un esperto nella vostra nicchia di blog.
Molti dei migliori plugin per social media consentono di mostrare il numero totale di follower nei feed incorporati, nei pulsanti, nei banner e altro ancora.
Tuttavia, a volte si può desiderare di mostrare il numero come testo semplice. Questo vi dà la libertà di aggiungere il numero di follower ai post del blog, al piè di pagina o in qualsiasi altro punto del vostro blog o sito web WordPress.
Tenendo presente questo, vediamo come visualizzare il numero di follower di Twitter come testo in WordPress.
Passo 1: ottenere una chiave API e un segreto di Twitter
Per ottenere il conteggio dei follower, è necessario accedere all’API di Twitter creando una chiave API e un segreto.
Per ottenere queste informazioni, visitate il portale degli sviluppatori di Twitter e fate clic su “Iscriviti all’account gratuito”.
Ora è possibile digitare alcune informazioni su come si intende utilizzare l’API di Twitter. È una buona idea fornire il maggior numero di dettagli possibile, poiché Twitter esaminerà queste informazioni e potrebbe cancellare il vostro account se non capisce come state usando la loro API.
Dopodiché, leggete i termini e le condizioni. Se siete soddisfatti di continuare, cliccate sul pulsante “Invia”.
A questo punto si aprirà il Portale sviluppatori. Nel menu di sinistra, fare clic per espandere la sezione “Progetti e applicazioni”. Quindi, selezionare “Panoramica”.
A questo punto è possibile fare clic su “Aggiungi app”.
Dopodiché, digitate il nome che desiderate utilizzare per la vostra applicazione Twitter. Questo è solo un riferimento, quindi potete usare qualsiasi cosa vogliate.
A questo punto, fare clic sul pulsante “Avanti”.
Twitter mostrerà ora una chiave API e un segreto API. Questa è l’unica volta che vedrete queste informazioni, quindi annotatele in un posto sicuro.
Si consiglia di aggiungere la chiave e il segreto a un gestore di password per una maggiore sicurezza.
Fase 2: Aggiungere il codice personalizzato al vostro sito WordPress
Il modo più semplice per aggiungere il conteggio dei follower di Twitter al vostro sito è utilizzare il codice PHP.
Per motivi di sicurezza, WordPress non consente di aggiungere codice PHP direttamente alle pagine e ai post, ma consente gli shortcode. Ciò significa che è possibile creare uno shortcode personalizzato e poi collegarlo al codice PHP.
Il modo più semplice per aggiungere shortcode personalizzati in WordPress è utilizzare WPCode. Questo plugin consente di creare tutti gli shortcode che si desidera e di collegarli a diverse sezioni del codice PHP.
La prima cosa da fare è installare e attivare il plugin gratuito WPCode. Per maggiori dettagli, consultate la nostra guida passo-passo su come installare un plugin di WordPress.
Dopo l’attivazione, andare su Code Snippets “ Add Snippet.
Qui vengono visualizzati tutti gli snippet già pronti che potete aggiungere al vostro sito web. Questi includono snippet che consentono di disabilitare completamente i commenti di WordPress, di caricare file che WordPress non supporta di default e altro ancora.
Poiché si sta creando un nuovo snippet, passare il mouse su “Aggiungi il tuo codice personalizzato”. Quindi, fare clic su “Usa snippet”.
Per iniziare, digitate un titolo per lo snippet di codice personalizzato. Può essere qualsiasi cosa che aiuti a identificare lo snippet nella dashboard di WordPress.
Successivamente, è necessario aprire il menu a tendina “Tipo di codice” e selezionare “Snippet PHP”.
Nell’editor di codice, incollare il seguente codice PHP:
function getTwitterFollowers($screenName = 'wpbeginner')
{
// some variables
$consumerKey = 'YOUR_CONSUMER_KEY';
$consumerSecret = 'YOUR_CONSUMER_SECRET';
$token = get_option('cfTwitterToken');
// get follower count from cache
$numberOfFollowers = get_transient('cfTwitterFollowers');
// cache version does not exist or expired
if (false === $numberOfFollowers) {
// getting new auth bearer only if we don't have one
if(!$token) {
// preparing credentials
$credentials = $consumerKey . ':' . $consumerSecret;
$toSend = base64_encode($credentials);
// http post arguments
$args = array(
'method' => 'POST',
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => 'Basic ' . $toSend,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
),
'body' => array( 'grant_type' => 'client_credentials' )
);
add_filter('https_ssl_verify', '__return_false');
$response = wp_remote_post('https://api.twitter.com/oauth2/token', $args);
$keys = json_decode(wp_remote_retrieve_body($response));
if($keys) {
// saving token to wp_options table
update_option('cfTwitterToken', $keys->access_token);
$token = $keys->access_token;
}
}
// we have bearer token wether we obtained it from API or from options
$args = array(
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => "Bearer $token"
)
);
add_filter('https_ssl_verify', '__return_false');
$api_url = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
$response = wp_remote_get($api_url, $args);
if (!is_wp_error($response)) {
$followers = json_decode(wp_remote_retrieve_body($response));
$numberOfFollowers = $followers->followers_count;
} else {
// get old value and break
$numberOfFollowers = get_option('cfNumberOfFollowers');
// uncomment below to debug
//die($response->get_error_message());
}
// cache for an hour
set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);
update_option('cfNumberOfFollowers', $numberOfFollowers);
}
return $numberOfFollowers;
}
echo getTwitterFollowers(); ?>
Nel codice qui sopra, assicurarsi di sostituire i seguenti segnaposto con la propria chiave API e il proprio segreto API:
$consumerKey = 'YOUR_CONSUMER_KEY';
$consumerSecret = 'YOUR_CONSUMER_SECRET';
È inoltre necessario sostituire “wpbeginner” con l’account Twitter che si desidera utilizzare. Può trattarsi di qualsiasi account Twitter, compresi quelli che non si possiedono:
function getTwitterFollowers($screenName = 'wpbeginner')
Per ottenere il nome utente di Twitter, basta aprire il profilo di Twitter in una nuova scheda. Il nome utente si trova nell’URL e nell’intestazione del profilo:
Fatto questo, tornate alla dashboard di WordPress. Qui è sufficiente fare clic sulla levetta “Inattivo” in modo che diventi “Attivo”.
A questo punto è possibile fare clic sul pulsante “Salva snippet”.
A questo punto, scorrere fino alla sezione “Inserimento”.
WPCode può aggiungere automaticamente il codice in diverse posizioni, ad esempio dopo ogni post, solo nel front-end o solo per gli amministratori. Per ottenere lo shortcode, basta cliccare sul pulsante “Shortcode”.
Ora è possibile utilizzare lo shortcode per aggiungere la riprova sociale a qualsiasi pagina o post.
Nell’editor dei blocchi, è sufficiente fare clic sul pulsante “+” e digitare “Shortcode”. Quando appare, selezionare il blocco Shortcode per aggiungerlo alla pagina o al post.
Ora è possibile aggiungere lo shortcode al blocco.
Tenete presente che lo shortcode mostra semplicemente il numero totale di follower, quindi in genere è necessario aggiungere un testo che spieghi il significato del numero.
Per ulteriori informazioni su come inserire lo shortcode, consultare la nostra guida su come aggiungere uno shortcode in WordPress.
Quando si è soddisfatti di come è impostata la pagina, si può rendere attivo il conteggio dei follower facendo clic sul pulsante “Aggiorna” o “Pubblica”.
Ora, se visitate il vostro sito WordPress, vedrete il conteggio dei follower in tempo reale.
Speriamo che questo tutorial vi abbia aiutato a capire come visualizzare il conteggio dei follower di Twitter come testo in WordPress. Potreste anche voler imparare a creare un feed fotografico Instagram personalizzato in WordPress o dare un’occhiata ai nostri esperti che hanno scelto i migliori plugin Twitter per WordPress.
Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.
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!
Jiří Vaněk says
I’ve also set up a Twitter account for my website to increase its reach. It might be nice to use this article and display the numbers in the posts. Perhaps, as part of marketing, it might encourage some readers to also join as followers. It could enhance the integration with social media and improve website traffic.
venky says
Hi used the same code in my site..but its not showing the follower counter of the twitter pages
pls help me out ..
Noraly says
update: after having one last look I saw I hadn’t activated the access token. So now it does show up, only way at the bottom of my sidebar. How do I move it up to a more logical place? Preferably within the text widget at the top, so I can include it with all my other social media links. Thank you!
Noraly says
Hi all, hope you are still monitoring comments, since it’s an older article. I have copied the code in functions.php, replaced the key and secret (left the ‘ ‘ intact, was I meant to do that?). Then I copied the other bit in sidebar.php. Replaced the yourscreenname with my twittername. This doesn’t make it show up in the sidebar though. Should I do something with a text widget in the sidebar, where I want it to show up? Just putting the last line of code in a sidebarwidget doesn’t seem to be the trick. Would appreciate your help. Thanks!
WPBeginner Staff says
Yes with a few changes you can use it with any PHP application.
Jitendra says
Can i use it in other PHP application? I mean any other application which is not WP.
arun says
It is not working for me.
I have added that code into sidebar template , then i replaced consumer key and secret key with screen name. Still it is not working
This is my page url
WPBeginner Support says
Arun it seems like you resolved the issue, when we visited your webpage it was showing the correct twitter follower count in plain text.
Admin
Nic Granleese says
Hi,
Can you tell me if this code works for multiple twitter users.
I’m trying to make a table with different users on a site with their respective twitter follow count.
When I tried it seems to display only one twitter user’s count, which I assume is because user one get’s cached, and then the second, third, and n users just display the same result.
Nic
WPBeginner Support says
Yes you got that right.
Admin
Thomas says
I’ve got the same problem.
When I ask for the follower count of three different accounts and display it on a page, it displays the same number three times. The number it displays is the exact follower count of the first account.
Do you know how to fix this? :/
Thanks in advance.
Thomas
Julian Lara says
Its possible to get a comma in the number like 140,029. Because actually show like 140029.
rayuribe says
works great!
but…
It is possible add the result of this script to this other >
http://lineshjose.com/blog/how-to-display-facebook-fans-count-as-text-in-wordpress-site/
and show the total? (facebook_fans+twitter_fans=total_fans)
jahirul says
Would you please share the code of follower count of yours? the function and the activation code, please.
Nazar says
This doesn’t work for me.
I’ve replaced $consumerKey and $consumerSecret as well as made the Access level to “Read and write” but nothing is happening
irfan says
Hey hi,
Such a great post.
I have ask a question for you I use twiiter user link (https://twitter.com/screen_name) when i use this link show followers its that possible?
Any one,
Thank Advance
Alvin says
Hello,
we get this error
Fatal error: Call to undefined function get_option() in line 17
line 17 is this
$token = get_option(‘cfTwitterToken’);
Matt says
Hi,
Dreamweaver tells me this line is invalid:
$api_url = “https://api.twitter.com/1.1/users/show.json?screen_name=$screenName“;
So I’ve updated it to:
$api_url = ‘https://api.twitter.com/1.1/users/show.json?screen_name=$screenName’;
But the twitter count just says 0 (I have over 1,200).
Any suggestions?
Thanks!
Matt
Malcom Miles says
Wrapped this tutorial along with the “WordPress Site Specific Plugin” tutorial and worked like a charm.
Many thanks! :3
jahirul says
would you give me the code or the link of your plugin please.
Tyler says
I’ve tried doing this atleast 10 times and can’t get it to work. Is it up-to-date?
Editorial Staff says
Yes this code was recently updated, and it works fine for us.
Admin
jahirul says
Does it work in localhost with net connection?
Zulhilmi Zainudin says
How about to display Facebook Fans & Google+ Followers in text?
Chandra says
Thanks for this code. I used this in my site but after sometime, I tested with an addition of follower but that count is not being updated. It still shows old count. Is something missing ? Thanks.
Chandra says
Ah, it updated after an hour or so…
regnar says
A little demo would be great.
Editorial Staff says
It will show the count as text. For example: if you have 100 followers, then it will output 100. Not sure what you expected in the demo.
Admin