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

Cómo mostrar el recuento de seguidores de Twitter y más en WordPress

Hemos escrito anteriormente acerca de un código que le permite mostrar el recuento de seguidores de Twitter que fue contribuido por Rarst. En este artículo, vamos a compartir un código más avanzado y más elegante que le permite mostrar el recuento de seguidores de Twitter en WordPress. Una vez más este script también fue contribuido por Rarst.

Características

Esta función no se limita al recuento de seguidores. Puede obtener cualquier valor no anidado devuelto por el método de la API Twitter users/show.

Tiene dos niveles de caché:

  • los valores consultados se almacenan como array en la base de datos, usando las opciones de WP, durante $intervalos de segundos;
  • Las respuestas de la API se almacenan en memoria para que pueda consultar cualquier número de campos, sin generar múltiples solicitudes de API.

Esto debería ser seguro de usar para multiplicar los valores y multiplicar los usuarios al mismo tiempo, sin preocuparse acerca de agotar el límite de la API.

Tutorial

Primero abre el archivo functions.php de tu tema y añade el siguiente código:

    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 vez que haya pegado la función, ahora puede utilizar el código en cualquier archivo de plantilla de WordPress que desee. Simplemente pegue el siguiente código:

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

El código anterior mostrará algo como esto:

WPBeginner tiene 5846 seguidores después de 1300 actualizaciones.

Fuente: Rarst

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

10 comentariosLeave a Reply

  1. 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…

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

  3. 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.

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.