Tutorial: Flash and WordPress (Part 1)

A quick search produced 2 excellent plugins that already does this, mainly the excellent Flash API, and the JSON API. We will be using the Flash API for this tutorial.

The Flash API actually provides a sample FLA and also, sample services for you to retrieve posts and even a simple NextGEN Image Gallery. However, the example only populates the data into a List Component. This is where this tutorial comes in, I will try to bridge this gap, and get you started with the Flash API plugin and start retrieving some posts!

Step 1: Installing the plugin

Since you’re reading this, I expect that you already have a WordPress installation somewhere and is ready to go. So go ahead and install the Flash API plugin.

Once that is done, activate the plugin, and then click on Generate Key.

Note down the API Key and also the Web Service URL, you’ll need it soon.

Step 2: Locating and editting the Flash Example

Next, look for the Flash example inside wp-content/plugins/flash-api/flash_example/. You should see a file named flash_api_example.fla inside.

Download and open the file, take a look at the actionscript and replace line 20 with the API key you generated earlier, and line 24 to your web service URL.

Go ahead and publish the FLA and see what you get. The example actually retrieves all the attachments that you have on your WordPress installation, and lets you download them. If you don’t have attachments on your installation, then you won’t see anything. But that’s not what people want to do normally, so let’s take a look at what other services we can call using the Flash API.

Take a look at services.php from the flash-api plugin folder. The default services are:

  • attachments
  • gallery (requires the gallery value)
  • sendmail
  • posts

What we want really, are the posts for now, so go ahead and change line 21 to posts. Publish your SWF, you should see a list of your post titles. If you try clicking on download, you’ll be linked to the post of your blog. But what we probably want, is to get the post’s body content.

I’ve went ahead and modified the 2 functions in the Flash file to do this. Replace the 2 functions with the ones from here:

// CONVERT A NODE INTO AN OBJECT
function objectifyAttr(node:XML):Object {
	var obj:Object = {};

	// Loop through attributes
	for (var a:uint = 0; a < node.attributes().length(); a++) {
		var attr:String = String(node.attributes()[a].name());
		var val:* = node.attributes()[a];
		obj[attr] = val;
	}
	//allocates the attribute postbody with the post content to the object
	obj['postbody'] = node.valueOf()
	return obj;
}

// DOWNLOAD CLICKED -> DOWNLOAD FILE
function downloadFile(evt:MouseEvent):void {
	var sel:String = (lst['selectedItem']) ? lst.selectedItem.postbody : null;
	if (sel != null) {
		//traces the content instead of going to the link of the post.
		trace(lst.selectedItem.postbody)
		//var u:URLRequest = new URLRequest(lst.selectedItem.link);
		//navigateToURL(u);
	}
}

And that’s it! Congratulations, you’ve successfully retrieved your WordPress posts in Flash! Hopefully, this tutorial will kickstart you to creating your own Flash frontend pulling data from the WordPress database.

I’ll be working on Part 2 of this tutorial soon and hopefully, I can extend the Flash API plugin with more services.

NextGEN Image Gallery WordPress Plugin – XML Output

Just going to paste a quick code snippet here. Hopefully, this is part one of a series of tutorials/snippets to show you how to use WordPress as a CMS to power a Flash frontend photo gallery.

All you need to do is to to upload this file into the wp-content/plugins/nextgen-gallery/xml folder.

Code here:

<?php

/*

//----------------------------------------------------------------+

 CUSTOM XML FOR NEXTGEN GALLERY
 By Edwin Toh (www.designfission.com)

//----------------------------------------------------------------+

*/

if ( !defined('ABSPATH') ) 

    require_once( dirname(__FILE__) . '/../ngg-config.php');

global $wpdb, $ngg, $nggdb, $wp_query;

$gallerylist = $nggdb->find_all_galleries('gid', 'asc', TRUE, 25, $start, false);

$ngg_options = get_option ('ngg_options');

$siteurl	 = site_url();

// get the gallery id

$galleryID = (int) $_GET['gid'];

// get the pictures

if ($galleryID == 0) {

	$thepictures = $wpdb->get_results("SELECT t.*, tt.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE tt.exclude != 1 ORDER BY tt.{$ngg_options['galSort']} {$ngg_options['galSortDir']} ");

} else {

	$thepictures = $wpdb->get_results("SELECT t.*, tt.* FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid WHERE t.gid = '$galleryID' AND tt.exclude != 1 ORDER BY tt.{$ngg_options['galSort']} {$ngg_options['galSortDir']} ");

}

// Create XML output

header("content-type:text/xml;charset=utf-8");

echo "<album>\n";

$gallerylist = $nggdb->find_all_galleries('gid', 'asc', TRUE, 0, 0, false);

if($gallerylist) {
	foreach($gallerylist as $gallery) {

		$class = ( !isset($class) || $class == 'class="alternate"' ) ? '' : 'class="alternate"';
		$gid = $gallery->gid;
		$name = (empty($gallery->title) ) ? $gallery->name : $gallery->title;
		$author_user = get_userdata( (int) $gallery->author );

		$picturelist = $nggdb->get_gallery($gid, $ngg->options['galSort'], $ngg->options['galSortDir'], false, 50, $start );

		echo "	<gallery>\n";

		echo "		<title>".stripslashes($name)."</title>\n";
		echo "		<description>".$gallery->galdesc."</description>\n";

		if (is_array ($picturelist)){

			foreach ($picturelist as $picture) {

				echo "		<image>\n";

				echo "			<title>".$picture->alttext."</title>\n";
				echo "			<description>".$picture->description."</description>\n";
				echo "			<url>".$siteurl."/".$picture->path."/".$picture->filename."</url>\n";
				echo "			<thumbnail>" . esc_url(nggGallery::i18n($picture->thumbURL)) ."</thumbnail>\n";

				echo "		</image>\n";

			}

		}

		echo "	</gallery>\n";

	}

}

echo "</album>\n";

?>

Opening a ColorBox in Flash

The update to my previous method to “Opening a Thickbox in iFrame” is finally here.

As you all know, ThickBox is no longer under development since 2007, the next popular alternative to take over the reigns of ThickBox seems to be ColorBox, and so I’ve done a new tutorial to do the same thing with ColorBox.

There are a few things that remain the same from the other example.

Step 1: Prepare your HTML.

Include the source files to ColorBox’s CSS, and Javascript files, as well as the original jQuery JS files.

Insert in the tags of your HTML:

<link media="screen" rel="stylesheet" href="colorbox.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="colorbox/jquery.colorbox.js"></script>

Step 2: Insert the Flash

Using SWFObject, insert Flash in your HTML and remember to set the following 2 parameters: “allowScriptAccess” to “always” and “wmode” to “transparent“.

Insert in the tags of your HTML:

<script src="Scripts/swfobject_modified.js" type="text/javascript"></script>

Insert in the tags of your HTML:

<object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="550" height="200">
  <param name="movie" value="colorbox.swf">
  <param name="quality" value="high">
  <param name="wmode" value="transparent">
  <param name="swfversion" value="6.0.65.0">
  <!-- This param tag prompts users with Flash Player 6.0 r65 and higher to download the latest version of Flash Player. Delete it if you don’t want users to see the prompt. -->
  <param name="expressinstall" value="Scripts/expressInstall.swf">
  <param name="allowscriptaccess" value="always">
  <!-- Next object tag is for non-IE browsers. So hide it from IE using IECC. -->
  <!--[if !IE]>-->
  <object type="application/x-shockwave-flash" data="colorbox.swf" width="550" height="200">
    <!--<![endif]-->
    <param name="quality" value="high">
    <param name="wmode" value="transparent">
    <param name="swfversion" value="6.0.65.0">
    <param name="expressinstall" value="Scripts/expressInstall.swf">
    <param name="allowscriptaccess" value="always">
    <!-- The browser displays the following alternative content for users with Flash Player 6.0 and older. -->
    <div>
      <h4>Content on this page requires a newer version of Adobe Flash Player.</h4>
      <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" width="112" height="33" /></a></p>
    </div>
    <!--[if !IE]>-->
  </object>
  <!--<![endif]-->
</object>
<script type="text/javascript">
swfobject.registerObject("FlashID");
</script>

Step 3: Prepare the Javascript Function

Because ColorBox does some parsing of the Javascript functions and ExternalInterface doesn’t seem to be able to call functions with the dollar sign in them. What I’ve done here is to create a simple javascript function and use Flash to call this very function.

Insert in the tags of your HTML:

<script>

	function launchColorBox(url){
		$.colorbox({href:url,width:"80%", height:"80%",iframe:true});
	}

</script>

Step 4: The Flash Code!

The final step is to actually reuse the Flash Code in my previous version, making only slight changes. Create a button with the instance name “btn1″ and put the code in the first frame of your Flash file.

stop()
//Imports the ExternalInterface Class
import flash.external.ExternalInterface;

//Adds the CLICK eventlistener to the button btn1
btn1.addEventListener(MouseEvent.CLICK,openColorBox)

//Launches the JS function that we created earlier.
function openColorBox(e:MouseEvent){
	ExternalInterface.call("launchColorBox","http://www.google.com");
}

You can view the demo here and download the source files here.

Roundup of Mobile Frameworks

PhoneGap
Supports iPhone/iTouch, iPad, Google Android, Palm, Symbian and Blackberry
License: Open Source
This is perhaps exactly what most people are looking for. Open source, compatible with almost all mobile platforms, and filled with documentation. You don’t create webapps with this, you create apps that you can submit to the App Store or the Android Marketplace.

Sencha
Supports mainly iOS and Android devices
License: US$99 for a single developer
Probably has the best documentation and supports touch gestures and more. The default UIs are very similar to what you find on Apple devices. Deploys as WebApp.

jQueryMobile
Supports iPhone/iTouch, iPad, Google Android, Palm, Symbian and Blackberry
License: Unknown
An upcoming framework to recreate UIs for mobile platforms. This will definitely make waves when it is released. Deploys as WebApp.

jQTouch
Supports iPhone and devices that uses browsers that support WebKit
License: MIT Licensed
One of the more popular frameworks. jQTouch has been around for some time and has a substantial fanbase. Documentation is good, and Peepcode has even created a screencast($9) and cheatsheet to get people started. Deploys as WebApp.

DHTMLX Touch
Supports iPhone and devices that uses browsers that support WebKit
License: GNU GPL and Commercial License
Thanks to Paul for bringing this to my attention. DHTMLX Touch is a free HTML5-based JavaScript library for building cross-platform mobile web apps. It’s not just a set of UI widgets, but a complete framework that allows you to create eye-catching, robust web applications for mobile and touch devices.

iUI
Supports iPhone and comparable/compatible devices.
License: Open Source
This is quite a basic framework that supplies users with iPhone like user interfaces. Picking it up might be hard though as there are hardly any documentation or articles on getting started. Deploys as WebApp.

WebApp.Net
Supports iPhone and comparable/compatible devices.
License: Free to use

SproutCore
Supports iPhone and comparable/compatible devices.
License: Unknown
Serves as a plugin to Ruby I think. Sorry I can’t give more info as I do not know Ruby.

Cappuccino
Supports iPhone and comparable/compatible devices.
License: LGPL
This is more than a mobile framework. Cappuccino is used to power applications that sits in a browser. If you’ve tried the popular wireframing tool: MockingBird, you should know how much it feels like a native desktop app. A special mention as it does allow you to create some wonderful mobile apps, if you want to.

Tools
iPhone Web Simulator
Adobe Dreamweaver CS5 HTML5 add-on
The Great Webkit Comparison Table

Credits:
Adrian Kosmaczewski’s excellent slides on SlideShare about Mobile Frameworks

If you think there is a mobile framework that deserves to be on this list, and would be helpful to would be mobile app developers, feel free to leave a comment below.

short – bringing back sweet old AS2 syntax to AS3

A new AS3 framework has been released by Arul @ Luracast. Do check it out at http://code.google.com/p/short/.

I’m pretty excited about it because of 2 things. Firstly, it’s the first framework released by someone based in Singapore. Secondly, I share the same frustration as the creator – a simple getURL that used to be so simple now takes more than 3 lines of code to create!

And lastly, if you’re based in Singapore, do check out the upcoming Flex User Group (fug) meeting that’s on this Wednesday (8 Sep 2010). RSVP at Facebook.

Special Thanks

Special thanks to GamingFuzz for buying those AdSpaces on DesignFission. Do head over to the website by clicking on the banners on the right to check out the website for game reviews and news!

Updated Portfolio

I’ve updated my 3 year old portfolio to a temporary wordpress portfolio so that I can showcase my latest work and find it easier to update than the current one. The old site can still be accessed via http://www.qwertydesign.net/v1/ and the new site can be accessed here.

The theme is a free WordPress theme from FROGSTHEMES.COM.

New Webhost!

Since most of my visitors are from USA, I’ve switched hosts to BlueHost.com. Hopefully, this site loads faster for you guys now!

SaltFilms Website wins!

This is a website that’s done by Driv - my Art Director at Kinetic, and “flashed” by Craig – my Flash mentor.

Congrats to them both for winning the FWA site of the day award!

Enjoy the beautifully crafted and executed site at http://www.saltfilms.com.sg

Essential Classes for Flash Developers

XML2Object (AS2)

Documentation / Download

Developed by sephiroth, one of the Flash gurus in the Flash community, XML2Object does what it’s name says. It converts an XML to an Object. Easily, I might add.

Pros:

  • Allows you to access XML elements just like an object.

Example:
Transform the passed XML source into an XML readable Object.

import it.sephiroth.XML2Object;
var dataObj:XML = new XML ();
//
dataObj.ignoreWhite = true;
var sXML:String = "path/to/xml_file.xml";
function handleLoad (success:Boolean) {
	if (success) {
		_root.xmlObj = new XML2Object ().parseXML (dataObj);
	}
}
//
dataObj.onLoad = handleLoad;
//Load the data
dataObj.load (sXML);

Cons:

  • It doesn’t detect a single item as an array. This is a problem if, for example, you load a gallery, and there’s only 1 item in the gallery. Your code will be built to entertain more than 1 item but it will not recognise a single item as an array.

?

Bitmap Exporter (AS2/3)

Documentation | Download

There are alot of classes that utilises the ByteArray to export whatever that is in Flash to an image, but for AS2, this is pretty much the only available one. (Do let me know if there’s a better one.)
As mentioned earlier, the Bitmap Exporter allows you to export a movieclip from Flash with predefined width, height and quality settings.

Pros:

  • Probably the only class that allows you to do this with AS2.

Cons:

  • Utilises the server heavily.
  • The exporting takes some time.

Transform Manager (AS2)

Documentation | Download

Ever wanted to create an application just like Photoshop? Well, maybe not exactly like Photoshop, but at least to allow your users to create their own customise their very own [insert brand object here].
The Transform Manager by Grant Skinner does the job perfectly. For me, the class makes rotating, scaling, moving and deleting objects very intuitive. However, usability experts might argue that users who are not used to Photoshop or any other image editing tools might find it a problem. Nevertheless, this is an awesome tool to have, and building on top of the class is possible as gskinner has graciously released the classes with the source code.
Like TweenMax, Grant’s documentation is awesome and is impossible to not understand.
Note: The link I posted above is to an older version that is free, the current and newer version costs $299. An AS3 version is also available but you will need to join the Club Greensock to get it.
?

Sephiroth Color Picker Component (AS2)

Documentation/ Download : http://www.sephiroth.it/file_detail.php?id=147

This is a UI Component that was never added by Flash. Thanks to Sephiroth though, you now get a lightweight, Color Picker Component for free.

There are dozens of classes released by the great Flash community all the time, and it will be impossible to list them all in this one article, what I’ve listed here are the ones I find myself reusing or has benefited me greatly.
You’ll also realise that I have not added any Tweening engines to this article as I believe they deserve to have a list on their own. Also, the classes listed here are mainly AS2. I will be sharing a similar list for AS3 soon.
Please feel free to add in more classes or components that you believe should be in this list.