4
Apr
Last.FM Top Albums WP Plugin
I’ve been meaning to package this into a proper WordPress plugin but have been too lazy/busy/etc. In the meantime, here it is in it’s raw form.
Oh, what it does is get your top albums from Last.FM and displays the album art in a pretty table. The XML file gets cached so it wont make an API call to the Last.FM servers on each page load.
It uses simplexml so you’ll need to be running at least php 5.
Dirty Install: Add your username and API key, create a folder in your wordpress plugins directory called CCO-LastFM_Top_Albums and save the below code in index.php of said directory. Call the function in your template.
<?php
/*
Plugin Name: Last.FM Top Albums
Plugin URI: http://www.chaoscontrol.org/wordpress/lastfm-top-albums-wp-plugin
Description: Gets your top played albums (with art) from last.fm
Version: 1.0
Author: Chris Sprague
Author URI: http://www.chaoscontrol.org/about
License: GPL2
*/
/* Copyright 2011 Chris Sprague (email : chris@chaoscontrol.org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
function last_fm_top_albums() {
// Your Last.FM Username
$user = '';
// Last.FM API Key (http://www.last.fm/api/account)
$api = '';
// overall | 7day | 3month | 6month | 12month
$period = "7day";
// Number of albums to pull
$limit = '10';
// Number of rows to display on
$rows = '2';
$as = 'http://ws.audioscrobbler.com/2.0/';
$method = '?method=user.gettopalbums';
$uri = $as;
$uri .= $method;
$uri .= '&user=' . $user;
$uri .= '&period=' . $period;
$uri .= '&limit=' . $limit;
$uri .= '&api_key=' . $api;
$cachedFile = WP_PLUGIN_DIR . '/CCO-LastFM_Top_Albums/' . $user . '.xml';
$cachedTTL = '300'; // Number of seconds
if (!file_exists($cachedFile) OR (filemtime($cachedFile) < time() - $cachedTTL)) {
$xml = file_get_contents($uri);
$fh = fopen($cachedFile, 'wb+');
fwrite($fh, $xml);
fclose($fh);
}
$xml = simplexml_load_file($cachedFile);
$div = $limit / $rows;
$i = 1;
echo '<p>';
foreach ($xml->topalbums->album as $album) {
echo '
<a href="' . $album->url . '">
<img src=' . $album->image . ' class="album_art" />
</a>';
if ($i >= $div) {
echo '</p><p>';
$i = 1;
} else {
$i++;
}
}
echo '</p>';
}