Wordpress Chartbeat Plugin

(2010)

Instead of doing something useful this morning, I made my own little plugin using the Chartbeat API to display the most popular posts on a Wordpress blog.

Note: There is really no reason to do this. The Chartbeat Plugin does this exact same thing and more. However, it was an entertaining exercise for me to practice writing wordpress plugins.

Also Note: This only works if you have signed up for Chartbeat and get an API Key.

The reason this is cool? Well, most of your "most popular posts" plugins need to make an extra call to the database to get/set a counter because wordpress doesn't track page views by default. But if you're using chartbeat to track your blog's performance, you can save some effort by using their numbers instead.

And with no further ado, here's the code:

<?php
/*
Plugin Name: My Most Popular
Version: 0.1
*/

$ct_most_popular_plugin_version = "0.1";

$ct_most_popular_plugin_data = array();

// create a most_popular option
register_activation_hook(__FILE__, 'ct_most_popular_plugin_install');
function ct_most_popular_plugin_install()
{
    add_option("ct_most_popular_plugin_data", $ct_most_popular_data);
    add_option("ct_most_popular_plugin_version", $ct_most_popular_plugin_version);
    // schedule hourly update
    wp_schedule_event(time(), 'hourly', 'ct_most_popular_plugin_update_event');
}

// delete the most_popular option
register_deactivation_hook(__FILE__, 'ct_most_popular_plugin_uninstall');
function ct_most_popular_plugin_uninstall()
{
    delete_option("ct_most_popular_plugin_data");
    delete_option("ct_most_popular_plugin_version");
    // un-schedule hourly update
    wp_clear_scheduled_hook('ct_most_popular_plugin_update_event');
}

// appear under "Settings" on the admin page
add_action('admin_menu', 'ct_most_popular_plugin_menu');
function ct_most_popular_plugin_menu() {
    add_options_page('Ct Most Popular', 'Ct Most Popular', 'manage_options', '', 'ct_most_popular_plugin_options');
}

// init option values in db
add_action('admin_init', 'ct_most_popular_plugin_options_init' );
function ct_most_popular_plugin_options_init(){
    register_setting('ct_most_popular_plugin_options', 'ct_most_popular_plugin', 'ct_most_popular_plugin_validate' );
}

// sanitize and validate input
function ct_most_popular_plugin_validate($input) {
    $input['host'] =  wp_filter_nohtml_kses($input['host']);
    $input['chartbeat_api_key'] =  wp_filter_nohtml_kses($input['chartbeat_api_key']);
    $input['limit'] =  (int)($input['limit']);
    if($input['limit'] == 0) $input['limit'] = 10;
    return $input;
}

// display options page html
function ct_most_popular_plugin_options() {
    if (!current_user_can('manage_options'))  {
        wp_die(__('You do not have sufficient permissions to access this page.') );
    }
?>
<div class="wrap">
    <h2>Ct Most Popular Plugin Options Title</h2>
    <form method="post" action="options.php">
        <?php settings_fields('ct_most_popular_plugin_options'); ?>
        <?php $options = get_option('ct_most_popular_plugin'); ?>
        <table class="form-table">
        <tr valign="top">
            <th scope="row">Host</th>
            <td><input type="text" name="ct_most_popular_plugin[host]" value="<?php echo $options['host']; ?>" /></td>
            <td><i>ie, example.com</i></td>
        </tr>
        <tr valign="top">
            <th scope="row">Chartbeat API Key</th>
            <td><input type="text" name="ct_most_popular_plugin[chartbeat_api_key]" value="<?php echo $options['chartbeat_api_key']; ?>" /></td>
            <td><i><a href="http://chartbeat.com/apikeys/">http://chartbeat.com/apikeys/</a></i></td>
        </tr>
        <tr valign="top">
            <th scope="row">Limit</th>
            <td><input type="text" name="ct_most_popular_plugin[limit]" value="<?php echo $options['limit']; ?>" /></td>
            <td><i>number of items to show, 10</i></td>
        </tr>
        </table>
        <p class="submit">
            <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
        </p>
        <p>
        This plugin uses the <a href="http://chartbeat.pbworks.com/">Chartbeat API</a> to show the most popular pages on your site, updated hourly.
        </p>
        <p>
        This plugin was created for my own amusement and to practice creating Wordpress plugins, it is <strong>NOT RECOMMENDED</strong> for use.
        </p>
        <p>
        Chartbeat has released a perfectly good plugin that does this and more: <a href="http://wordpress.org/extend/plugins/chartbeat/">http://wordpress.org/extend/plugins/chartbeat/</a>
        </p>
        <p>
        This plugin fetches new data once every hour using Wordpress's built-in <a href="http://codex.wordpress.org/Function_Reference/wp_schedule_event">scheduling hooks</a> to update the list of popular posts hourly.
        This keeps things self-contained, but doesn't provide much flexibility. You may want to use cron instead, which would require a little hacking.
        </p>
    </form>
</div>
<?php
}

// get popularity data from chartbeat, store in db
add_action('ct_most_popular_plugin_update_event', 'ct_most_popular_plugin_update_chartbeat');
function ct_most_popular_plugin_update_chartbeat() {
    // construct chartbeat call
    $options = get_option('ct_most_popular_plugin');
    $host = $options['host'];
    $apikey = $options['chartbeat_api_key'];
    $limit = $options['limit'];
    // build url
    $url = 'http://api.chartbeat.com/toppages/?host=HOST&amp;limit=LIMIT&amp;apikey=APIKEY';
    $url = str_replace('HOST', $host, $url);
    $url = str_replace('APIKEY', $apikey, $url);
    $url = str_replace('LIMIT', $limit, $url);
    // fetch data
    $data = file_get_contents($url);
    $data = json_decode($data, true);
    // exit if not enough results back
    if(count($data) < $limit)
        return;
    $result = array();
    for($i=0; $i<count($data); $i++) {
        if($data[$i]['path'] == "/")
            continue;
        $result[] = $data[$i];
    }
    $result = array_slice($result, 0, $limit);
    // store in db
    update_option("ct_most_popular_plugin_data", $result);
}

// add this function in your sidebar
function ct_most_popular_plugin_widget() {
    $data = get_option("ct_most_popular_plugin_data");
    echo('<ul>');
    foreach ($data as $post) {
        echo('<li>');
        echo('<a href="'.$post['path'].'">'.$post['visitors'].'-'.$post['i'].'</a>');
        echo('</li>');
    }
    echo('</ul>');
}

Go to "Settings" > "Ct Most Popular" to set your API Key and other options.

Updates occur once each hour.

You'll almost certainly want to tweak the way the posts are displayed in the ct_most_popular_plugin_widget() function.

Anyway.. just fooling around.. For all the frustration it has caused me.. Still gotta say, Wordpress is pretty friggin' cool.