Ajax Flickr Widget – WordPress

I recently wanted to have my Flickr photostream displayed in the sidebar of this site. I couldn’t find a simple widget that would display my photostream without having to hack a bunch of CSS to make it match my site, I also needed to photos to load in after site load because it’s a bit heavy on the images. I needed a better solution, so I decided to build my own. The result is almost ready to be released for WordPress as a plugin. Just a few minor cleanup issues.

Basically, it works off the phpflickr library, users fill out a simple form to get started and the module loads the most recent photos in the photostream asynchronously in order to ensure the site’s fastest possible load time.

I thought it might be helpful to quickly review how to write an ajax enable WordPress 3.0+ plugin:

Initialize the Widget:

class Flickr_Gallery extends WP_Widget {
	function Flickr_Gallery() {
		 $widget_ops = array(
		 'classname' => 'flickrgallery',
		 'description' => 'Displays most recent flickr photos from the stream according to a specified username.');
		$control_ops = array(
		 'width' => 250,
		 'height' => 250,
		 'id_base' => 'flickrgallery-widget');

		 $this->WP_Widget('flickrgallery-widget', 'Flickr Gallery', $widget_ops, $control_ops );
	}

Output a form where users can fill in the necessary information:

// produce the form for the widget
function form ($instance) {
$defaults = array('catid' => '1', 'numberposts' => '5');
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<p>
<label for="<?php echo $this->get_field_id('key'); ?>">API Key:</label>
<input type="text" name="<?php echo $this->get_field_name('key') ?>" id="<?php echo $this->get_field_id('key') ?> " value="<?php echo $instance['key'] ?>" size="20"> </p>
<p>
<label for="<?php echo $this->get_field_id('secret'); ?>">Secret:</label>
<input type="text" name="<?php echo $this->get_field_name('secret') ?>" id="<?php echo $this->get_field_id('secret') ?> " value="<?php echo $instance['secret'] ?>" size="20"> </p>
<p>
<label for="<?php echo $this->get_field_id('username'); ?>">Username:</label>
<input type="text" name="<?php echo $this->get_field_name('username') ?>" id="<?php echo $this->get_field_id('username') ?> " value="<?php echo $instance['username'] ?>" size="20"> </p>
<p>
<label for="<?php echo $this->get_field_id('numberphotos'); ?>">Number of Photos per Page:</label>
<select id="<?php echo $this->get_field_id('numberphotos'); ?>" name="<?php echo $this->get_field_name('numberphotos'); ?>">
<?php for ($i=1;$i<=99;$i++) {
$i = $i * 3;
echo '<option value="'.$i.'"';
if ($i==$instance['numberphotos']) echo ' selected="selected"';
echo '>'.$i.'</option>';
} ?>
</select>
</p>
<?php
}
// produce the form for the widgetfunction form ($instance) {
 $defaults = array('catid' => '1', 'numberposts' => '5');  $instance = wp_parse_args( (array) $instance, $defaults ); ?>
 <p>     <label for="<?php echo $this->get_field_id('key'); ?>">API Key:</label>     <input type="text" name="<?php echo $this->get_field_name('key') ?>" id="<?php echo $this->get_field_id('key') ?> " value="<?php echo $instance['key'] ?>" size="20"> </p>
 <p>     <label for="<?php echo $this->get_field_id('secret'); ?>">Secret:</label>     <input type="text" name="<?php echo $this->get_field_name('secret') ?>" id="<?php echo $this->get_field_id('secret') ?> " value="<?php echo $instance['secret'] ?>" size="20"> </p>    <p>     <label for="<?php echo $this->get_field_id('username'); ?>">Username:</label>     <input type="text" name="<?php echo $this->get_field_name('username') ?>" id="<?php echo $this->get_field_id('username') ?> " value="<?php echo $instance['username'] ?>" size="20"> </p>    <p>   <label for="<?php echo $this->get_field_id('numberphotos'); ?>">Number of Photos per Page:</label>   <select id="<?php echo $this->get_field_id('numberphotos'); ?>" name="<?php echo $this->get_field_name('numberphotos'); ?>">   <?php for ($i=1;$i<=99;$i++) {		$i = $i * 3;        echo '<option value="'.$i.'"';        if ($i==$instance['numberphotos']) echo ' selected="selected"';        echo '>'.$i.'</option>';     } ?>    </select>  </p>
 <?php}

Create a standard "Save" function:


// save the widget
function update ($new_instance, $old_instance) {
$instance = $old_instance;

$instance['numberphotos'] = $new_instance['numberphotos'];
$instance['key'] = $new_instance['key'];
$instance['secret'] = $new_instance['secret'];
$instance['username'] = $new_instance['username'];

return $instance;
}

Output the widget:

// print the widget
function widget ($args,$instance) {
	extract($args);
	$key = $instance['key'];
	$secret = $instance['secret'];
	$username = $instance['username'];
	$numberphotos = $instance['numberphotos'];
	echo $before_widget;
	echo $before_title.$title.$after_title;
	// load in your custom output function below
	echo customeOutputFunction();
	echo $after_widget;
}

We must also have a function to register the widget with WordPress:

// register the widget
function load_flickr_gallery() {
register_widget('Flickr_Gallery');
}

Finally, add the hook that will register the widget when WordPress loads widgets:

//add_action('widgets_init', 'load_flickr_gallery');
add_action('widgets_init', create_function('', 'return register_widget("Flickr_Gallery");'));

Now, if we want ajax functionality, add:

// Function for handling AJAX requests
function flickr_gallery_handler() {
	// Check that all parameters have been passed
	if ((isset($_GET['mywidget_request']) && ($_GET['mywidget_request'] == 'some_action')) && isset($_GET['page'])) {
		$fpage = (int)$_GET["page"];
		if($fpage < 99){
			echo outputGallery($key, $secret, $username, $numberphotos, $fpage);
			exit();
		} else {
			echo "The page you requested is too large!";
			exit();
		}
	} elseif (isset($_GET['mywidget_request']) && ($_GET['mywidget_request'] == 'some_action')) {
		// Otherwise display an error and exit the call
		echo "Error: Unable to display request.";
		exit();
	}
}

And add the ajax handler to the init():

// Add the handler to init()
add_action('init', 'flickr_gallery_handler');

Now simply include some sort of ajax script to the front end in order pass the request:

jQuery(document).ready(function(){
	function ajaxLoadGallery(dest) {
		jQuery("#gallery-container div.page, #gallery-container ul, #gallery-container p").fadeOut();
		jQuery.ajax({
			type    : "GET",
			url     : "index.php",
			data    : { mywidget_request    : "some_action",
						page : dest
						},
			success : function(response) {
				// do something with the server response here

			}
		});
	}
});

And your all set!

Feel free to add any other functions outside this class, or inside for that matter, just remember not to violate any WordPress reserved function names you should be able to add any function you want!

3 thoughts on “Ajax Flickr Widget – WordPress

  1. Hello, any update on the wordpress plugin? Is it available yet?

    Thanks so much for this code!

  2. This code can’t work it seems. Biggest problem I see is finding away to get instance variables from the widget to the ajax request method…
    in function flickr_gallery_handler(). you have this:

                echo outputGallery($key, $secret, $username, $numberphotos, $fpage);

    From what I see all those variables you are passing in, are undefined. or am I missing an important part?

  3. Hi! Do you know if they make any plugins to help with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not
    seeing very good success. If you know of any please share.
    Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *