TwitterWP — A WordPress tool to get you connected to the Twitter 1.1 API

While updating my DsgnWrks Twitter Importer, I took the time to abstract the “Connect to Twitter” part. This will hopefully be an invaluable tool to anyone working with Twitter’s API in WordPress, or has clients that need their old Twitter 1.0 code updated.

Here is the (hopefully up-to-date) example.php that comes with the download:

<?php

if ( ! class_exists( 'TwitterWP' ) )
  require_once( 'lib/TwitterWP.php' );

/**
 * Example TwitterWP usage
 */
add_action( 'all_admin_notices', 'twitterwp_example_test' );
function twitterwp_example_test() {
  // app credentials
  // (must be in this order)
  $app = array(
    'consumer_key'        => 'YOUR CONSUMER KEY',
    'consumer_secret'     => 'YOUR CONSUMER SECRET',
    'access_token'        => 'YOUR ACCESS TOKEN',
    'access_token_secret' => 'YOUR ACCESS TOKEN SECRET',
  );
  // initiate your app
  $tw = TwitterWP::start( $app );

  // Also works:
  // $tw = TwitterWP::start( '0=CONSUMER_KEY&1=CONSUMER_SECRET&2=ACCESS_TOKEN&3=ACCESS_TOKEN_SECRET' );

  $user = 'jtsternberg';
  // bail here if the user doesn't exist
  if ( ! $tw->user_exists( $user ) )
    return;

  echo '<div id="message" class="updated">';
  echo '<pre>'. print_r( $tw->get_tweets( $user, 5 ), true ) .'</pre>';
  echo '</div>';

  // Now let's check our app's rate limit status
  $rate_status = $tw->rate_limit_status();
  echo '<div id="message" class="updated">';

  if ( is_wp_error( $rate_status ) )
    $tw->show_wp_error( $rate_status );
  else
    echo '<pre>'. print_r( $rate_status, true ) .'</pre>';

  echo '</div>';

}

The library comes with several methods to connect to different API endpoints:

  • Check if a user exits
    $tw->user_exists( $user = '' );
  • Get a number of a user’s tweets
    $tw->get_tweets( $user = '', $count = 1 );
  • Get a number of search term tweets
    $tw->get_search_results( $search, $count = 100 );
  • Get a number of tweets from a user’s list
    $tw->get_list_tweets( $user = '', $list = '', $count = 1 );
  • Access the user profile endpoint
    $tw->get_user( $user = '' );
  • Check your apps rate limit status
    $tw->rate_limit_status( $params = array() );
  • A generic helper for querying twitter via the bearer token.
    $tw->token_endpoint( $trail, $params = array() );
  • Returns your twitter app credentials (if they exist)
    $tw->get_app_creds();

Fork/Clone/Download TwitterWP on GitHub.

2 Comments on “TwitterWP — A WordPress tool to get you connected to the Twitter 1.1 API

  1. Pingback: Manage Code Snippets in WordPress with the Code Snippets Custom Post Type Plugin

Comment

Fast, secure WordPress hosting is provided by WP Engine.
%d bloggers like this: