WordPress Extjs – Displaying Posts in an ExtJS Grid

Now that the WP-ExtJS Plugin is complete, I figured, I’d create a post to show a use case. Today, I’ll be showing how you might use this plugin to display your blog posts in an ExtJS Grid using PHP and MySQL – and the WordPress built-in functions for accessing blog post data.

Requirements

Getting Started

We’re going to walk through the steps required to create an ExtJS GridPanel that contains all of the WordPress Posts from your blog.

Let’s take a quick look at the result first:
[wp-extjs snippet_id=”1012″ height=300]

There are two components to this example. The first is the data provider and the second is the ExtJS Script which will render the grid component.

Data provider script

We could use PHP to directly render data from a MySQL database – but I figured, I’d make use of data that I have laying around in my WordPress blog. WordPress comes with a bunch of really handy scripts that let you source the data from your blog from PHP scripts.

To accomplish this, you must first set up your WordPress environment inside your script to enable access to the WordPress data. This is done by including the wordpress functions and configuration scripts.

[php]
include_once(‘../../../wp-config.php’);
include_once(‘../../../wp-config.php’);
include_once(‘../../../wp-load.php’);
include_once(‘../../../wp-admin/includes/taxonomy.php’);
include_once(‘../../../wp-includes/wp-db.php’);
[/php]

Now that we have our environment setup, we can use the WordPress function query_posts to access our posts. This function takes an argument which can be an array of optional arguments. I’m telling WordPress to limit the number of posts per page to 25.
[php]
query_posts(array(
‘posts_per_page’ => 25
));
[/php]

This sets up a queue of posts which we can loop through using another WordPress function called have_posts(). Now we can reference the attributes of each post sequentially using get_the_ID(),get_the_title(), get_the_content(), etc.

I’m using a temporary array variable in my loop to accumulate the blog post data. Once I have the elements of the post I want to use in my grid columns, I add them to the array variable.

Once the posts have been collected into a PHP array variable, I want to print them in JSON format. PHP added the json_encode function starting at version 5.2 which makes this task very simple. However, if you don’t have version 5.2 or higher, you can include this handy script and let it do the work for you.

You should place this script somewhere under your webroot – and be sure to tailor the relative links to your WordPress installation for the include statements. The script below expects to be in a subdirectory of your wp-content/plugins directory under the WordPress root. If you move the script or put it somewhere else, be sure you change the include statements so that it knows where to find the WordPress includes and functions.

Once you have the script in place, test it by pointing your browser directly to it… you should see the content of your blog posts in JSON format displayed in your browser window. If you do not – something is not right and you’ll need to whip out your favorite debugging tool. I prefer FireBug for Firefox.

Here is the entire script:
[php]
<?php
/**
* wp-posts-json.php – Part of the WP-ExtJS Plugin
* Renders wordpress posts in json format
* @author Michael Lynn
* @version $Id$
* @copyright Michael Lynn, 6 December, 2010
**/

define(‘WP_USE_THEMES’, false);

include_once(‘../../../wp-config.php’);
include_once(‘../../../wp-config.php’);
include_once(‘../../../wp-load.php’);
include_once(‘../../../wp-admin/includes/taxonomy.php’);
include_once(‘../../../wp-includes/wp-db.php’);

query_posts(array(
‘posts_per_page’ => 25
));

$tmp = array();
$arr = array();

while(have_posts()) {
$count_posts = wp_count_posts();
$total = $count_posts->publish;

the_post();
$tmp["id"] = get_the_ID();
$tmp["title"] = get_the_title();
$tmp["url"] = apply_filters(‘the_permalink’,get_permalink());
$tmp["content"] = wp_filter_nohtml_kses(apply_filters(‘the_content’,get_the_content()));
$tmp["date"] = get_the_time(‘Y-F-d’);
$arr[]=$tmp;
}

if (version_compare(PHP_VERSION,"5.2","<"))
{
require_once("JSON.php"); //if php<5.2 need JSON class
$json = new Services_JSON();//instantiate new json object
$data=$json->encode($arr); //encode the data in json format
} else
{
$data = json_encode($arr); //encode the data in json format
}

echo ‘({"total":"’ . $total. ‘","data":’ . $data . ‘})’;
[/php]

JSON stands for JavaScript Object Notation and is a convenient, easy to read data format. We could have used XML – but I find it easier to work with JSON in my PHP scripts. You can find more information on JSON at json.org.

Here’s what the output of this script looks like (I’ve shortened the code by replacing the content of the post with “…”.

{ "data" : [ { "date" : "2010-December-06",
        "id" : 1010,
        "title" : "WordPress Extjs – Displaying Posts in an ExtJS Grid",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/12/wordpress-extjs-displaying-posts-in-an-extjs-gri/"
      },
      { "date" : "2010-November-26",
        "id" : 990,
        "title" : "WP-ExtJS Examples",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/11/wp-extjs-treepanel-example/"
      },
      { "date" : "2010-November-23",
        "id" : 960,
        "title" : "WP-ExtJS Chart Example",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/11/wp-extjs-chart-example/"
      },
      { "date" : "2010-November-22",
        "id" : 885,
        "title" : "Publish ExtJS Snippets inside WordPress Pages or Posts",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/11/wp-extjs/"
      },
      { "date" : "2010-November-19",
        "id" : 764,
        "title" : "Create a custom sidebar for each page or post with this Graceful Sidebar WordPress Plugin",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/11/graceful-sidebar-plugin/"
      },
      { "date" : "2010-October-24",
        "id" : 746,
        "title" : "I know where you live – WP Geocode WordPress Plugin Ready for Release",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/10/wp-geocode-plugin/"
      },
      { "date" : "2010-September-06",
        "id" : 637,
        "title" : "Domain Wizard (domwiz.com) Hits the Scene with Instant Domain Name Lookups",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/09/domain-wizard-domwiz-com-hits-the-scene-with-instant-domain-name-lookups/"
      },
      { "date" : "2010-August-09",
        "id" : 487,
        "title" : "How to Monitor your Mac Desktop with Dropbox",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/08/how-to-monitor-your-mac-desktop-with-dropbox/"
      },
      { "date" : "2010-July-20",
        "id" : 303,
        "title" : "Mobile Device Detection and Redirection with Perl and CGI",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/07/mobile-device-detection-and-redirection-with-perl-and-cgi/"
      },
      { "date" : "2010-July-14",
        "id" : 300,
        "title" : "SOLVED: My WordPress Thumbnails Stopped Thumbnailing",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/07/solved-my-wordpress-thumbnails-stopped-thumbnailing/"
      },
      { "date" : "2010-June-30",
        "id" : 240,
        "title" : "Mobile Device Detection and Redirection with PHP",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/06/mobile-device-detection-and-redirection-with-php/"
      },
      { "date" : "2010-March-21",
        "id" : 205,
        "title" : "Find Your Domain Name, Whatever It Might Be",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/03/domain-name-checker/"
      },
      { "date" : "2010-March-19",
        "id" : 174,
        "title" : "10 Tips to Help You Become a Better ExtJS, PHP, MySQL Developer",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/03/10-tips-to-help-you-become-a-better-extjs-php-mysql-developer/"
      },
      { "date" : "2010-February-16",
        "id" : 161,
        "title" : "Projects and Payroll",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/02/projects-and-payroll/"
      },
      { "date" : "2010-February-15",
        "id" : 136,
        "title" : "Visio Diagram – Highly Available Database",
        "content" : "...",
        "url" : "http://www.mlynn.org/2010/02/visio-diagram-highly-available-database/"
      }
    ],
  "total" : "15"
}

ExtJS Snippet – Grid Panel

Now that we have our blog post data in JSON format, we can begin creating our ExtJS Grid snippet. To do this, we’ll be using the WP-ExtJS Plugin. Once you have the plugin installed and configured to find your extjs installation, creating a snippet is as easy as creating another WordPress Post.

Simply, click on the ExtJS Snippets “Add New” menu and provide the source of the ExtJS script. We’re going to be instantiating an ExtJS GridPanel component.

As with any ExtJS component, you need to create the requisite data and configuration objects. The gridpanel component is very well documented over at sencha.com.

Here’s the script we’re going to create:

Ext.onReady(function(){

var store = new Ext.data.Store({
	url: 'http://www.mlynn.org/wp-content/plugins/wp-extjs/wp-posts-json.php',
	reader: new Ext.data.JsonReader({
		root: 'data',
		totalProperty: 'total',
		fields: [
		  {name: 'id', type: 'int'}, 
		  {name: 'title', type: 'string'},
		  {name: 'url', type: 'string'},
		  {name: 'content', type: 'string'},
		  {name: 'date', type: 'date'}
		]
	})
});

store.setDefaultSort('id');

var cm = new Ext.grid.ColumnModel([{
    id: 'ID',
    header: "ID",
    dataIndex: 'id',
    width: 20,
  },{
    header: "Date",
    dataIndex: 'date',
    width: 40,
	renderer: Ext.util.Format.dateRenderer('m/d/Y')
  },{
    header: "Title",
    dataIndex: 'title',
    width: 190
  },{
    header: "Content",
    dataIndex: 'content',
    width: 270
  },{
    id: 'url',
    header: "URL",
    dataIndex: 'url',
	renderer: renderUrl,
    width: 150
}]);

cm.defaultSortable = true;

var grid = new Ext.grid.GridPanel({
	height: 500,
	renderTo: 'grid',
    store: store,
    cm: cm,
    sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
    loadMask: true,
    viewConfig: {
      forceFit:true
},
bbar: new Ext.PagingToolbar({
  pageSize: 25,
  store: store,
  displayInfo: true,
  displayMsg: 'Displaying Posts {0} - {1} of {2}',
  emptyMsg: "No Posts to display"
})
});

grid.render();
store.load();

function toggleDetails(btn, pressed) {
    var view = grid.getView();
    view.showPreview = pressed;
    view.refresh();
}
function renderUrl(value) {
	return '<a href='+value+'>'+value+'</a>';
}
});	

This script is fairly straight forward and consists of configuration objects for the datastore, the columnmodel and the gridpanel. The datastore is configured with a url parameter which tells the datastore where we’re going to be fetching data. We also tell the datastore that we’re going to be receiving JSON encoded data and configure it with a JsonReader.

At this point you should have everything you need to duplicate the post examples within your own blog. Simply cut and paste the ExtJS script and create a new ExtJS Snippet. Be sure you use the Additional Body Fields field in the ExtJS Snippet edit screen to provide a div container for the grid panel. You will notice on line 50 of the ExtJS script, we’re telling the gridpanel that it will be rendering to a div called “grid”.

	renderTo: 'grid',

Here’s a zip archive containing the ExtJS Snippet (in posts.html) and the php script file wp-posts-json.php.
[download id=”8″]

When attempting to use the downloaded script files, make sure you cut and paste the ExtJS Snippet starting with Ext.OnReady… I included the posts.html as a complete, stand-alone example. Also, as a reminder, you will need to modify the php script to ensure that it finds the wordpress include files.

Advertisements

One thought on “WordPress Extjs – Displaying Posts in an ExtJS Grid

  1. mike says:

    Testing new mailer for comment responses…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: