Wordpress as CMS, custom database and $_Get variables

Written: Dec 3rd 2007, 20:58


Screenshot Ironman.no - made with Wordpress


The great blog platform Wordpress does more than serve blogs. Lately I used it, and it’s build in classes for a new norwegian sports site: Ironman.no – hosting all norwegian triathlon results throughout history. Among the things we did there, was serving data from custom databases and ability to search and browse this data.



Basic consept using Wordpress (WP) as a CMS


First of all, WP got 2 kinds of main content types: Posts and Pages. With the later versions of WP you can easily suppress all the “weblog” stuff by going into the Options > Reading and select a static page as frontpage.


Further you can crate you own theme, where you can control the HTML and CSS WP does render. Best pracsis is to copy the default theme, and work you way through the different files.


And last, but not least, WP lets you define your own page templates, which you can use in your static pages. The templates of WP is pure PHP and you have access to both regular PHP functions and WP’s own classes and functions.

Extending Wordpress page templates

To create a custom page template, you just have to add this in the top of the template:


(php)
/* Template Name: (02) Page with results */ 
(php end)

And it will be available inside the standard Wordpress editor (www.domain.com/wp-admin)

Select custom templates in Wordpress admin


Use the build-in database class in Wordpress


Querying the athlete table for all athletes that has a homepage:


(php)
// Give wpdb with global scope<br />
global $wpdb; <br />
$sql = "SELECT athlete.name, athlete.url
FROM athlete 
WHERE athlete.url like '%http%' 
order by athlete.name asc"; 
$results = $wpdb->get_results($sql);
(php end)

With the function $wpdb->get_results($sql) you get your result returned as an object that you can iterate through:


(php)
foreach($results as $result) {
	echo $result->name;
	echo $result->url;
}
(php end)

Use forms and GET variables to perform queries


Next stop is to let your users do queries on your database. First up is adding a form element to your custom page:


<form method="get" action="<?php echo 
htmlspecialchars($_SERVER['SCRIPT_URI']) ?>">

I choose $_GET since the user than would be able to email his ironman results a friend.

(php)
// Check for $_GET variables
if (isset($_GET['theyear']) and is_numeric($_GET['theyear'])) {
	$theyear = (int)$_GET['theyear'];
}
(php end)

Resources when hacking Wordpress

Back to posts list