WordPress plugin DB access framework

While designing a recent WordPress plug-in for TruthMedia that was designed to follow MVC, I had an awful lot of database work to do, and it needed to all be properly secured, which was a lot of work, and while making a rather large change to the way the database worked, I realized that writing all the db code by hand was crazy inefficient.

So I wrote a class that you can extend with any model class of your own, and it will automatically have create, read, update, and delete functionality with no more work required. It also uses all of the WordPress security features to properly escape everything and prevent injection. Although, if you can crack it I’d love to hear from you!

Click here to download!

This is how it works:

  1. Create a new class (ex. person)
  2. Give that class instance variables (ID, FirstName, LastName, Address, PhoneNumber, PostalCode, HairColour…)
  3. Make sure that you add accessor methods (getters and setters) for the ID (although it’s good practice to have them for all instance variables). Depending on your project, it may be a good idea to run stripslashes() on your string get functions so that they don’t show up with escaping. You may want to run WordPress’ attribute_escape() on setters, however, again, depending on your set up this may be unnecessary.
  4. Write your SQL code to create a table named (wordPress prefix)(plugin prefix)person (ex. wp_wec_person)
  5. Make sure you call your primary Key personID **This is very important, without this, the system breaks down**
  6. If you wish to store variables in this class, you can modify them to be private, and they won’t be written to the database

In your class, extend the class name, so for example:

class person extends wec_db {

var $ID;

var $FirstName;

function __construct($id = null, $autoload = true){

//If we are given an ID
if(!empty($eventID)){

$this->setID($eventID);


if
($autoPopulate){

$this->read();

}

}

}

//getters and setters, and any other methods for this object

}

Setup Note: to keep your plugin from stepping on the toes of others, make sure you change the prefix at the top of the class. Also, changing the name of the class to (plugin prefix)db (example:wec_db) will make sure that it doesn’t interfere with anyone else’s if they’re using this class!

Usage:

Create / Add

$person = new person();

$person->setFirstName(‘Joe’);

$person->setLastName(‘Blow’);

$person->add();

Read

$person = new person($personID);

Update

$person = new person($personID);

–or–

$person = new person($personID, false);

$person->setFirstName(‘Jane’);

$person->update();

Delete

$person = new person($personID, false);

$person->delete();

Post any questions in the comments! I’d love to hear from you!

Facebook Comments

Cause a field to be auto-focused when the page is done loading

So, wouldn’t it be user friendly, if when you went to a form page in a document, if the cursor was automagically positioned at the first field in the form?

Why, yes it would. Try:

	
Event.observe(window, 'load', function(){
     try {
          $('eventName').focus();
     } 

     catch (e) {}
});

after your </form> tag. This requires the prototype javascript library

Facebook Comments

WordPress inline field validation for plugins

On a recent plugin, I’ve been looking for a way to have powerful form field validation, while being really user-friendly. Using AJAX to do run a PHP server-side check from a form (to ensure that somebody can’t have duplicates) is the best way I’ve found. This is basically the same as what you’ll find on the WordPress.org Codex, but shorter, and more specific for this application.

Code:

1. Add an action on the init() action to call the sack JS script (deals with AJAX in WP)

wp_enqueue_script ( ‘sack’ );

2. Create an instance of the sack object, and create variables to pass into the PHP side.

function doesCalendarExist(wpurl, confirmationFieldName, calendarNameFieldID, submitButtonID) {

var ajaxObject = new sack(wpurl + ‘/wp-admin/admin-ajax.php’);

ajaxObject.execute = 1;

ajaxObject.method = ‘POST’;

ajaxObject.setVar( “action”, “doesCalendarExist” );

ajaxObject.setVar( “confirmationField”, confirmationFieldName);

ajaxObject.setVar( “calendarName”, document.getElementById(calendarNameFieldID).value);

ajaxObject.setVar( “submitButton”, submitButtonID);

ajaxObject.onError = function(){ alert(‘Ajax error’)};

ajaxObject.runAJAX();

return true;

}

3. Create an input field that can call javascript functions to populate the data, and a span that will hold the error message

<input name=“calendarName” type=“text” id=“calendarName” onblur=”doesCalendarExist(<?php echo bloginfo(‘url‘); ?>’, ‘span1’, ‘calendarName’, ‘submitCalendarAdd’);/>

<span id=“span1″ class=”formError”></span>

4. Create a PHP function that will read the data passed from the ajaxObject. Die() statements will pass JavaScript back to the page. The dieString variable is super useful to be able to add lots of different DOM changes.

function wec_ajax_doesCalendarExist(){

$confirmationField = $_POST[‘confirmationField’];

$calendarName = $_POST[‘calendarName’];

$submitButton = $_POST[‘submitButton’];

$calendars = calendarDA::getAllcalendars();

$exists = false;

foreach($calendars as $calendar){

if(strcasecmp($calendar[‘calendarName’], $calendarName) == 0){

$exists = true;

}

}

if($exists){

$dieString = “document.getElementById(‘”. $confirmationField .“‘).innerHTML=’This calendar already exists!’;”;

$dieString .= “document.getElementById(‘”. $submitButton .“‘).disabled = true;”;

die($dieString);

}

else{

$dieString = “document.getElementById(‘”. $confirmationField .“‘).innerHTML=”;”;

$dieString .= “document.getElementById(‘”. $submitButton .“‘).disabled = false;”;

die($dieString);

}

}

5. Add a WordPress Action to the init() that maps the sack action to the PHP function. you have to add “wp_ajax_” to the beginning of your action name from sack. the second argument is the name of your function that this action will call

add_action(‘wp_ajax_doesCalendarExist’, ‘wec_ajax_doesCalendarExist’ );



Facebook Comments

Javascript example to do an auto-generated slug on a WordPress Plugin


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function duplicateField(field1, field2){
var theLength = document.getElementById(field1).value.length - 1;
var theString = document.getElementById(field1).value;
for(var i=0; i < theString.length-1; i++){
if(theString.charAt(i) == " "){
theString = setCharAt(theString, i, "_");
}
}
document.getElementById(field2).style.color = "#c9c9c9";
document.getElementById(field2).value = theString;
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
function changeColorBack(fieldName){
document.getElementById(fieldName).style.color = "#000000";
}
</script>
</head>
<body>
<p>
<input id="field1" onkeyup="duplicateField('field1', 'field2');" type="text" />
</p>
<p><br />
<input id="field2" type="text" onfocus="changeColorBack('field2');" /><br />
</p>
<p>
<span id="span1"></span>
<input id="submitButton" type="submit" value="Submit" />
</p>
</body>
</html>

Facebook Comments

Using WP_Query in WordPress 2.7

So I was trying for the last week or so to use three loops on a single page, to display categorized pages, and couldn’t figure out why it didn’t work. (I used the plugin page category plus to put pages in categories).

Anyways, if you want pages to be shown in a categorical listing, use post_type=page in the query string. Otherwise it’ll only show posts by default, which didn’t happen in previous versions! Mine looked like this: <?php $sportsQuery = new WP_Query(‘category_name=Sports Pages&post_type=page’); ?>

//Loop goes here…

Hope this helps somebody. I know I’ll be coming back to it when I forget!

For more info see: http://codex.wordpress.org/Template_Tags/query_posts

Facebook Comments

How to do multiple virtual hosts on OS X

  1. Download and install VirtualHostX (don’t forget to back up your existing config!!)
  2. Download and install Gas Mask (manages multiple hosts files, dumb name though)
  3. If you want to do this with WordPress and you have a database locally and another one on a dev server somewhere, you can do the following code:

if(eregi(“^mywebsitename.com$”, $_SERVER[HTTP_HOST]))

{

define(‘DB_NAME’, ‘dbremotename’);

/** MySQL database username */

define(‘DB_USER’, ‘dbremoteuser’);

/** MySQL database password */

define(‘DB_PASSWORD’, ‘dbremotepassword’);

/** MySQL hostname */

define(‘DB_HOST’, ‘dbremotehost’);

define(‘WP_SITEURL’, ‘http://mywebsitename.com’);

define(‘WP_HOME’, ‘http://mywebsitename.com’);

}

else{

define(‘DB_NAME’, ‘dbremotename’);

/** MySQL database username */

define(‘DB_USER’, ‘dblocaluser’);

/** MySQL database password */

define(‘DB_PASSWORD’, ‘dblocalpassword’);

/** MySQL hostname */

define(‘DB_HOST’, ‘dblocalhost’);

define(‘WP_SITEURL’, ‘http://mywebsitename.com’);

define(‘WP_HOME’, ‘http://mywebsitename.com’);

}

Facebook Comments

HTML Special Characters

Any good web designer knows certain characters have to be encoded in HTML.

Here’s a list of pretty much every character and it’s encoding: http://webdesign.about.com/library/bl_htmlcodes.htm

Bonus: Need to use some encoded characters in your PHP script? Use html_entity_decode() to turn them into regular text.

Facebook Comments

Recursive FTP

Fun thing I found today: how to copy a whole pile of files/folders over from one place to another using ftp. Especially useful on two remote computers in terminal when security isn’t a concern!
wget -r ftp://username: password@domainname

Facebook Comments