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

Come visualizzare il numero di follower di Twitter e altro ancora in WordPress

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Chi siamo ha già scritto di un codice che visualizza il numero di follower di Twitter, fornito da Rarst. In questo articolo condivideremo un codice più avanzato ed elegante che consente di visualizzare il conteggio dei follower di Twitter in WordPress. Anche questo script è stato fornito da Rarst.

Caratteristiche

Questa funzione non è limitata al conteggio dei follower. Può recuperare qualsiasi valore non annidato restituito dal metodo API Twitter users/show.

Ha due livelli di cache:

  • i valori interrogati sono memorizzati come array nel database, utilizzando le opzioni di WP, per $intervalli di secondi;
  • Le risposte API sono memorizzate, in modo da poter effettuare una query su qualsiasi numero di campi, senza generare richieste API multiple.

Questo dovrebbe essere sicuro da usare per moltiplicare i valori e moltiplicare gli utenti allo stesso tempo, senza preoccuparsi di esaurire il limite delle API.

Tutorial

Aprite il file functions.php del tema e aggiungete il seguente codice:

    function rarst_twitter_user( $username, $field, $display = false ) {
    $interval = 3600;
    $cache = get_option('rarst_twitter_user');
    $url = 'http://api.twitter.com/1/users/show.json?screen_name='.urlencode($username);

    if ( false == $cache )
    $cache = array();

    // if first time request add placeholder and force update
    if ( !isset( $cache[$username][$field] ) ) {
    $cache[$username][$field] = NULL;
    $cache[$username]['lastcheck'] = 0;
    }

    // if outdated
    if( $cache[$username]['lastcheck'] < (time()-$interval) ) {

    // holds decoded JSON data in memory
    static $memorycache;

    if ( isset($memorycache[$username]) ) {
    $data = $memorycache[$username];
    }
    else {
    $result = wp_remote_retrieve_body(wp_remote_request($url));
    $data = json_decode( $result );
    if ( is_object($data) )
    $memorycache[$username] = $data;
    }

    if ( is_object($data) ) {
    // update all fields, known to be requested
    foreach ($cache[$username] as $key => $value)
    if( isset($data->$key) )
    $cache[$username][$key] = $data->$key;

    $cache[$username]['lastcheck'] = time();
    }
    else {
    $cache[$username]['lastcheck'] = time()+60;
    }

    update_option( 'rarst_twitter_user', $cache );
    }

    if ( false != $display )
    echo $cache[$username][$field];
    return $cache[$username][$field];
    }

Uso

Una volta incollata la funzione, è possibile utilizzare il codice in qualsiasi template di WordPress. Basta incollare il seguente codice:

echo rarst_twitter_user('wpbeginner', 'name').' has '.
rarst_twitter_user('wpbeginner', 'followers_count').' followers after '.
rarst_twitter_user('wpbeginner', 'statuses_count').' updates.';

Il codice sopra riportato visualizza qualcosa di simile:

WPBeginner ha 5846 follower dopo 1300 aggiornamenti.

Fonte: Rarst

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

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.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

11 commentiLascia una risposta

  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. Aleks says

    Someone explain where I put in my own twitter username please? Cause I really cant see where… And I cant get it to work either… No matter what.. This just wont give me username, not even leaving it completly basic as it stands right now, I get no response on username what so ever… it just displays: “has followers after updates”…
     
    That’s it.. nothing else…

  3. Downhill_MC says

    this is a great code. i wonder if there is a possibility to create a function for embedding in text (something like ). downhill_mc

  4. Rarst says

    Glad you found it useful. :) Old snippet still works but it got kinda outdated and spread around a lot – it was getting hard to answer questions and correct outdated parts all the time.

    This one is slightly more bulky, but it has much extended functionality for showing more data and for different usernames at the same time.

    I also intend to maintain it more properly so feedback and suggestions are welcome on its page at my blog.

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.