Insert an image into a WordPress Post with a plugin.

So in a project I’m working on I need to use a normal form to insert a post into the database. My client wanted the form to also add an image to the post. Furthermore, the image must be inserted using normal WordPress methods. The code below is the minimum required to insert an image into the database and attach it to a specific post.

//	$id is the id of the post being inserted
//	$name is actually the name of the form input that uploaded the file so WP can access it using $_FILE[$name]

If you are inserting a new post, it makes sense to have the line $id = wp_insert_post($post_data); before this.

Short Ajax Script

AJAX - it

I wanted to see how small you could make a fully functional AJAX script that worked cross-browser and degraded gracefully, so I went through an old custom AJAX script and made it as small as I possibly could. In the resulting AJAX scripts, the post version is 410 characters and the GET version is only 359 characters long. The scripts are fully functional and accept the following parameters: URL, DATA (in string form), and ELEMENT (to update).

The scripts could be a little smaller, but it would really kill readability.

“Get” AJAX Script

function a(l,d,u){
try{r = new XMLHttpRequest();}catch(e){try {r = new ActiveXObject('Msxml2.XMLHTTP');}catch(e){r = new ActiveXObject('Microsoft.XMLHTTP');}}
r.onreadystatechange = function() {if (r.readyState == 4 && r.status == 200){document.getElementById(u).innerHTML = r.responseText;}}'GET', l+'?'+d, true);r.send(d);

“Post” AJAX Script

function b(l,d,u){
try{r = new XMLHttpRequest();} catch(e){try {r = new ActiveXObject('Msxml2.XMLHTTP');} catch(e){r = new ActiveXObject('Microsoft.XMLHTTP');}}
r.onreadystatechange = function() {if (r.readyState == 4 && r.status == 200){document.getElementById(u).innerHTML=r.responseText;}}'POST', l, true);r.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');r.send(d);

Combined AJAX Script

This combined script also accepts a fourth parameter ‘p’ that should evaluate true if the data is to be sent by post.

function a(l,d,u,p){
try{r = new XMLHttpRequest();}catch(e){try {r = new ActiveXObject('Msxml2.XMLHTTP');}catch(e){r = new ActiveXObject('Microsoft.XMLHTTP');}}
r.onreadystatechange = function() {if (r.readyState == 4 && r.status == 200){document.getElementById(u).innerHTML = r.responseText;}}
if(p){'POST', l, true);r.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');}else{'GET', l+'?'+d, true);}

Demo: (Sorry but you will have to go to the full page so the JavaScript is loaded.) Continue reading »

Custom Category Templates on a Archive or Index page.

On my home page and in my archives, I use a custom category template to display asides and news articles. This is very easy to do and it only takes a couple seconds of work to create custom category templates in any WordPress theme.

The first step is to add the following to your current theme’s index.php loop after the line that looks like <?php while (have_posts()) : the_post(); ?>, but before any other code.

<?php $cat_temp = cat_loop();?>
	<?php if($cat_temp && is_numeric($cat_temp)){?>
		<?php include('loops/cat_'.$cat_temp.'.php');?>
	<?php }else{ ?>

Then add } just before the line endwhile.

The next step is to add the following to your theme’s functions.php file (you may have to create a file with the same name):

function cat_loop(){
	global $blog_id,$post, $wp_version;
		if($wp_version >= 2.3){
			global $object_term_cache;
			$array = $object_term_cache[$blog_id][$post->ID]['category'];
			global $category_cache;
			$array = $category_cache[$blog_id][$post->ID];
		while (list($cat) = each($array)) {
				return $cat;

This can be modified to look at author’s also. Now the only thing you have to do is to create a folder named “loops” in your theme’s folder, and then create a new file with a new “loop” — excluding the while and endwhile parts — and name it cat_xxx.php where xxx is the id of the category the loops is for.

This can be repeated for single.php, archive.php, or anywhere else a custom loop is useful. You can even use something similar for individual posts or pages.

A post may be in multiple categories, but it will only use the first custom template it finds, so make sure the post is in only one specially styled category at a time.

Can’t connect to local MySQL server through socket…error.

I recently moved my /home folder to its own partition, but in doing so, I broke MySQL. The full error I got was:
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

To fix this you need to create the file and make sure that MySQL has access to it. (All commands need to be run as root)

Create the directory (if it doesn’t already exist).

sudo mkdir /var/run/mysqld/

Create the file by “touching” it.

sudo touch /var/run/mysqld/mysqld.sock

Set the ownership of the mysqld.sock file and folder to mysql.

sudo chown -R mysql /var/run/mysqld/

You can then start MySQL and breath easier.

DIY Javascript Effects Library

As part of a project I needed an extremely light-weight special effects library that would allow queuing of effects (required), multiple effects, the ability to set a per-effect “framerate”, and enough extensibility to fill any need, but it had to be independent of any Javascript library or OS.

For the “core”: I needed it to be able to queue effects to run one after another, but still be able to run effects synchronously with their own queues. Setting up the effects should take no more than a few lines, and the library should be easy adapted to the website or app it is currently running on. The library must also be cross browser, run well on lower end computers, and very very small (the main reason for creating it was as a replacement in a project for people who didn’t want to use jQuery or Scriptaculous just for the effects.) The core should be able to do everything with only being told the element’s ID, whether we are showing or hiding it (if applicable), and the effect to use. An added “feature” I wanted was something that could be used to create a tutorial, so no features could be used that were too fancy.

For the effects: I needed each individual effect to take no more than a few lines of setup, processing and finishing, so the framework needed to control everything, but each effect should be able to set its own duration using the framerate set. It should also be extremely simple to add new effects to the library.

The results: A library that is only 8KB in size (without compression or comments) or 2.9KB with natural (not gZip) compression and no comments with 4 built-in effects. While I’ll admit that the syntax to call effects isn’t as “pretty” as some of the other libraries, it is very simple, and queuing is powerful and easy to set up. If you want to jump ahead and see the finished product go here

This is just a demonstration post. The actual code will be explained in the future.

To test the effects library click here

The that group of effects was done with the following code:
AOI_eff.start('test_1', {'mode': 'show', 'eff': 'Expand', 'queue': ['hide::test_1::Fade','show::test_2::ScrollLeft::450','hide::test_2::ScrollLeft::50','show::test_1::Fade::25']} );

Something a little more interesting: here or the same thing, but with opposite displays here or the same thing, but the effects depend on the display. here

The onClick commands for those effects are, respectively, as follows.

AOI_eff.start('test_3', {'mode': 'show', 'eff': 'Expand', 'delay': 75, 'queue': ['show::test_4::Fade','show::test_5::ScrollLeft','show::test_6::SlideUp::50']} ); AOI_eff.start('test_5', {'mode': 'show', 'eff': 'Expand', 'delay': 75, 'queue': ['show::test_3::Fade']} );
AOI_eff.start('test_3', {'mode': 'hide', 'eff': 'Expand', 'delay': 75, 'queue': ['hide::test_4::Fade','hide::test_5::ScrollLeft','hide::test_6::SlideUp::50']} ); AOI_eff.start('test_5', {'mode': 'hide', 'eff': 'Expand', 'delay': 75, 'queue': ['hide::test_3::Fade']} );
AOI_eff.start('test_3', {'eff': 'Expand', 'delay': 75, 'queue': ['::test_4::Fade','::test_5::ScrollLeft','::test_6::SlideUp::50']} ); AOI_eff.start('test_5', {'eff': 'Expand', 'delay': 75, 'queue': ['::test_3::Fade']} );

As you can see this is still a work in progress, but I think over time it will improve greatly.

PHP include ladder to find include path.

I needed a way to be able to include particular files from files that are themselves included. because the working directory was not necessarily the same, so I needed a way to find what the actual include path should be. The following code snippet finds a specific folder or file and returns the ladder (relative path) to get to it.

function find_path($loc,$dir=0){
	for($i = 0; $i < 10; $i++){
				return $ladder;
			return $ladder;
		$ladder .='../';

This code is NOT user-input safe: any checks you do should be hard coded otherwise you might as well just give out your passwords.