Czy chcesz wyświetlać twoją liczbę obserwujących na Twitterze jako tekst w WordPress?
Pokazując, że wiele osób śledzi cię w mediach społecznościowych, możesz zachęcić odwiedzających do zaufania twojej witrynie internetowej. Co więcej, wyświetlając te informacje jako tekst, masz swobodę korzystania z nich w dowolnym miejscu na twojej witrynie internetowej, w tym we wpisach i na stronach.
W tym artykule pokażemy, jak wyświetlić twoją liczbę obserwujących na Twitterze jako tekst w WordPress.
Dlaczego warto wyświetlać obserwujących na Twitterze jako tekst w WordPress?
Być może zauważyłeś, że wiele popularnych blogów, influencerów i marek z dumą pokazuje, ile osób śledzi ich w mediach społecznościowych.
Jeśli odwiedzający widzą, że wiele osób śledzi Cię w mediach społecznościowych, są bardziej skłonni zaufać Twojej firmie i postrzegać Cię jako eksperta w Twojej niszy blogowej.
Wiele z najlepszych wtyczek do mediów społecznościowych pozwala wyświetlać całkowitą liczbę obserwujących w osadzanych kanałach, przyciskach, banerach i nie tylko.
Czasami jednak warto wyświetlić liczbę jako zwykły tekst. Daje to swobodę dodawania liczby obserwujących do wpisów na blogu, stopki lub w dowolnym innym miejscu na twoim blogu lub witrynie internetowej WordPress.
Mając to na uwadze, zobaczmy, jak wyświetlić twoją liczbę obserwujących na Twitterze jako tekst w WordPress.
Krok 1: Uzyskanie klucza API i sekretu Twittera
Aby uzyskać twoją liczbę obserwujących, musisz uzyskać dostęp do API Twittera, tworząc klucz API i sekret.
Aby uzyskać te informacje, przejdź do portalu dla programistów Twittera, a następnie kliknij „Zarejestruj darmowe konto”.
Możesz teraz wpisać rodzaj informacji o tym, jak planujesz korzystać z API Twittera. Dobrym pomysłem jest podanie jak największej ilości szczegółów, ponieważ Twitter sprawdzi te informacje i może usunąć twoje konto, jeśli nie zrozumieją, w jaki sposób korzystasz z ich API.
Następnie zapoznaj się z taksonomią. Jeśli chcesz kontynuować, kliknij przycisk „Prześlij”.
Wyświetli się portal dla deweloperów. W menu po lewej stronie kliknij, aby rozwinąć sekcję „Projekty i aplikacje”. Następnie wybierz „Przegląd”.
Możesz teraz przejść dalej i kliknąć „Dodaj aplikację”.
Następnie wpisz rodzaj nazwy, której chcesz użyć dla swojej aplikacji na Twitterze. To jest tylko dla twojego odniesienia, więc możesz użyć czegokolwiek chcesz.
Po zakończeniu kliknij przycisk „Dalej”.
Twitter wyświetli teraz klucz API i sekret API. To jedyny raz, kiedy zobaczysz te informacje, więc zanotuj je w bezpiecznym miejscu.
Zalecamy dodanie klucza prywatnego i tajnego do menedżera haseł w celu dodatkowego zabezpieczenia.
Krok 2: Dodaj własny kod do Twojej witryny internetowej WordPress
Najprostszym sposobem na dodanie liczby obserwujących na Twitterze do twojej witryny jest użycie kodu PHP.
Ze względów bezpieczeństwa WordPress nie pozwala na dodawanie kodu PHP bezpośrednio do twoich stron i wpisów, ale zezwala na krótkie kody. Oznacza to, że możesz utworzyć własny krótki kod, a następnie odnośnik do twojego kodu PHP.
Najprostszym sposobem na dodanie własnych shortcodes w WordPress jest użycie WPCode. Wtyczka ta umożliwia utworzenie dowolnej liczby krótkich kodów, a następnie powiązanie ich z różnymi sekcjami kodu PHP.
Pierwszą rzeczą, którą musisz zrobić, to zainstalować i włączyć darmową wtyczkę WPCode. Aby uzyskać więcej informacji, zobacz nasz przewodnik krok po kroku, jak zainstalować wtyczkę WordPress.
Po włączaniu udaj się do Code Snippets „ Add Snippet.
Tutaj zobaczysz wszystkie gotowe fragmenty kodu, które możesz dodać do swojej witryny internetowej. Obejmują one fragmenty kodu, które pozwalają całkowicie wyłączyć komentarze WordPress, przesyłać pliki, których WordPress domyślnie nie obsługuje, i nie tylko.
Ponieważ tworzysz nowy fragment kodu, najedź kursorem myszy na „Dodaj swój własny kod”. Następnie kliknij „Użyj fragmentu kodu”.
Na początek wpisz tytuł własnego fragmentu kodu. Może to być cokolwiek, co pomoże zidentyfikować fragment kodu w kokpicie WordPress.
Następnie należy otworzyć listę rozwijaną „Rodzaj kodu” i wybrać „Fragment kodu PHP”.
W edytorze kodu wystarczy wkleić następujący kod 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(); ?>
W powyższym kodzie upewnij się, że zastąpiłeś poniższe symbole zastępcze twoim własnym kluczem API i sekretem API:
$consumerKey = 'YOUR_CONSUMER_KEY';
$consumerSecret = 'YOUR_CONSUMER_SECRET';
Będziesz musiał również zastąpić „WPBeginner” kontem na Twitterze, którego chcesz używać. Może to być dowolne konto na Twitterze, w tym konta, których nie jesteś właścicielem:
function getTwitterFollowers($screenName = 'wpbeginner')
Aby uzyskać nazwę użytkownika Twittera, wystarczy otworzyć profil Twittera w nowej karcie. Nazwę użytkownika znajdziesz pod adresem URL i w nagłówku profilu:
Po wykonaniu tej czynności wróć do kokpitu WordPress. Tutaj wystarczy kliknąć przełącznik „Nieaktywny”, aby zmienił się na „Aktywny”.
Następnie możesz kliknąć przycisk „Zapisz fragment kodu”.
Po wykonaniu tej czynności przewiń do sekcji „Wstaw”.
WPCode może automatycznie dodawać twój kod do różnych miejsc, takich jak po każdym wpisie, tylko front-end lub tylko administrator. Aby uzyskać krótki kod, wystarczy kliknąć przycisk „Krótki kod”.
Możesz teraz użyć krótkiego kodu, aby dodać dowód społeczny do dowolnej strony lub wpisu.
W edytorze bloków wystarczy kliknąć przycisk „+” i wpisać „Krótki kod”. Po wyświetleniu wybierz blok Krótki kod, aby dodać go do strony lub wpisu.
Teraz możesz dodać krótki kod do bloku.
Należy tylko pamiętać, że krótki kod po prostu pokazuje całkowitą liczbę obserwujących, więc zazwyczaj warto dodać tekst wyjaśniający, co oznacza ta liczba.
Więcej informacji na temat umieszczania krótkiego kodu można znaleźć w naszym przewodniku na temat dodawania krótkiego kodu w WordPress.
Gdy jesteś zadowolony z konfiguracji strony, możesz aktywować liczbę obserwujących, klikając przycisk „Aktualizuj” lub „Opublikuj”.
Teraz, jeśli przejdziesz na swoją witrynę internetową WordPress, zobaczysz liczbę obserwujących na żywo.
Mamy nadzieję, że ten poradnik pomógł ci dowiedzieć się, jak wyświetlić twoją liczbę obserwujących na Twitterze jako tekst w WordPress. Możesz również dowiedzieć się, jak utworzyć własny kanał zdjęć Instagramu w WordPressie lub sprawdzić nasze wybory ekspertów dotyczące najlepszych wtyczek Twittera dla WordPressa.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and 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.
Administrator
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.
Administrator
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.
Administrator
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.
Administrator