WordPress and Ajax

adding the Ajax URL to the theme head

The file that handles all Ajax calls on WordPress is /wp-admin/admin-ajax.php. The URL for this file should be recognized with the client by defining it as a local javascript variable with the theme head:

function print_zw_rating_scripts () {
wp_register_script( 'my_ajax', plugins_url( 'my_ajax.js' , __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'my_ajax', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
if (!is_admin()) {
add_action('wp_print_scripts', 'print_zw_rating_scripts');

If all went well, viewing the page source on the browser, you should see this output:
A new object ‘my_ajax’, has been created within the global scope, and may be reached from your other scripts.

Adding ‘nonce’

Along with all the data we are passing to the server, we will also pass a security key:

$nonce = wp_create_nonce("my_user_vote_nonce");
<input type="hidden" value="<?php echo $nonce; ?>" name="ny_nonce" id="my_nonce" />

Setting the ajax function on the client side

this should go inside the javascript file:

jQuery(document).ready( function() {
jQuery(".my_action_button").click( function() {
ajax_data = jQuery('#ajax-data').val()
nonce = jQuery('$my_nonce').val();

type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_server_action", post_id : post_id, nonce: nonce, ajax_data: ajax_data},
success: function(response) {
if(response.type == "success") {
// do something
else {
// handle errors



Meanwhile, on the server side…

On our functions/plugin file we add the function that should take care of the data sent by the client:

function process_my_data() {
// validating the 'nonce' security key:
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");

$ajax_data = $_request['ajax_data'];

// if all is well - process the data ,and echo the results.
echo 'heres what you get back.';
// else: handle errors.
// always die at the end, otherwise, the admin-ajax.php will go on with a non relevant output...

Adding our action to the ajax queue

We hook our action on 2 action hooks. One for admin mode, and on for the front-end mode:

add_action("wp_ajax_my_server_action", "process_my_data");
add_action("wp_ajax_nopriv_my_server_action", "process_my_data");

Keep in minde that this hook connects the client action that is defined with the javscript function (in this case it’s name is: my_server_action), with the function defined on the server side: (named in our case “process_my_data”)

That’s it!

Wordrpess Importer hangs with sealed lips

Today I tried to import some content from another wordpress installation to mine. First off – I imported the XML file into my staging DB, and it all went well. Then I went on and tried to import it on the live server. At hitting the button – the page reloads for a while, and then – nothing.
I tried it a couple of times with no avail.
First thing – I have verified that the file is smaller than the max file size limit set on the server. It was.
So I went ahead to seek help from Mr. Google, but all I came up with was a load of rants and rackets about the WordPress Importer plugin. That meant I need to roll up my sleeves and get my hands dirty with raw plugin code…
Making a long story short – it all comes down to this line:
$dom = new DOMDocument;
within the WXR_Parser_SimpleXML class, in a file named parser.php of the importer plugin. And at that – the plugin cannot be blamed. Thing is – when calling the DOMDocument class, if it is not installed on the server , it will return nothing. Nesting this call inside a try and catch will not do either. This might be an issue with WordPress, and maybe turning on debug mode can help, I admit I haven’t checked it.
So only thing left is indeed to check if the libxml and the domdocument extensions are indeed installed with the server. They are probably not, so setting them with the server is most likely to solve the problem.

Cake PHP first steps

So having gone through the Blog tutorial and the Simple authentication tutoiral, I have come across my first rode bump: a really ugly exception: PHP Fatal error: Class 'AppController' not found in /var/www/lib/Cake/Controller/CakeErrorController.php on line ...

At that I was completely lost. So I went for help from Mr. Google.

The first search result I have stumbled upon was in Italian, but I would never let such a trifle to stop me. I realized there may be a way to drill further down this error, if I set right my error handling level with the debugger: add (modify) this line in your app/config/core.php: Configure::write('debug', 2);

Unfortunately this line is already set in there.

So I went on for the second result. There I have found out that PHP5.4 would allow this syntax: $this->Auth->user()['role'] while in older version you would rather use: $user = $this->Auth->user()
$role = $user['role'];

I am not syaing this piece of info was completely irrelevant. It was in fact, indirectly. Because it taught me 2 things:

  1. Cake is looking for the error controller to alert about a problem, and at not finding it – would alert about the missing error handler. Instead of alerting about the actual probelm, it would whine about it’s issues with the error handling.
  2. Good to know you can use this syntax in new versions of PHP!

Off-course at this stage I am still at a loss about the issue that had caused all this in the first place. So I go for the 3rd, 4th … results, and I come across this very helpful link by Oxford Rob (from whom I have also borrowed the quotation) with some very usefull lead: It is all in the appcontroller.php file. Here’s where we start to debug.

So first stage is to set a new fresh copy of this file, instaed of the one we’re having – at doing that – the application is loading correctly. With that I get a couple of more civilized error messages that I am going to take care of later on.

So now I am going to add back gradually everything that was in the appcontroller so I am able to tell where exactly everything should fall apart. And here it is: public $components = array('DebugKit.Toolbar');

What is this DebugKit.toolbar – I really know nothing of. But at least I am able to go on and try to look it up. I am now left with two unsolved issues:

  1. The error handler issue is still not solved.
  2. I am left with a more civilized error message: Error: The application is trying to load a file from the DebugKit plugin on my application’s main page. So that’s probably the next thing I need to try and fix.

Upgrading WordPress – A Peack under the Hood

What happens when we click Upgrade Now?

  • WordPress creates automatically a file named .maintenance
  • All these files might be overriden:
    • All the files under /wp-includes/
    • All the files under /wp-admin/
    • Any wordpress’ original theme folder (Twentyten, Twentyeleven etc..) under wp_content/
    • All files directly under wordpress’ root
  • A couple of files/folders may be added to wp_content/
  • On the database, The “db_upgraded” flag on the wp_options table is set to “0”
  • If all went well, WordPress deletes automatically the .maintenance file

Once done, the right db and system versions are recorded on the wp_config.php file:
* The WordPress version string
* @global string $wp_version
$wp_version = '3.1.3';

* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.
* @global int $wp_db_version
$wp_db_version = 17516;

If anything goes wrong – here’s an interesting article with some suggestions for troubleshooting.

Adding Scripts and Style only to a certain Page on WordPress

Sometimes we want to add a script or a css file only to a certain page. How can this be done?

Here’s what happened to me: I needed to insert a code snippet on a page. The snippet was generated by a third party. In fact – it was a form, and the form’s code, already ready, also contained the action for the form, on a galaxy far, far away. I.e. – remote server, not a part of the site.

That means – most of the work already done. All is needed is to paste the piece of code on a page, and let the 3rd party action page deal with the rest. Unfortunately, even when a remote server takes care of the form data, it is still our responsibility to validate it on the client side. So further to adding the html code for the form, we need some javascript to actually validate it. To do so, I wanted to call an external jquery plugin called validationengine. Question is: how do I call this script only on the form’s page?

So the first thing we do, is create a unique template for the form page. Having done that we go on to the next stage

What we need to do now, is creating 2 hooks that will be called and affect the content of the page’s head. The first hook, when called, will register the necessary js files, and the second hook will add a line to the head html: a call for the css file.

In this example I will demonstrate adding some script that take care of form validation, but you may use the same technique for anything you want.

So it is time to add some code to our functions.php file. You can find this file on your theme’s directory. If you don’t find it – don’t worry. Just go ahead and create one. Open the functions.php file with your favorite text editor and write down:
function print_form_scripts () {
wp_enqueue_script('validationEngine-en', get_bloginfo( 'template_url' ).'/jquery.validationEngine-en.js', array('jquery'));
wp_enqueue_script('validationEngine', get_bloginfo( 'template_url' ).'/jquery.validationEngine.js', array('jquery'));
function print_form_styles ($content) {
$content .= '<link rel="stylesheet" href="'.get_bloginfo( 'template_url' ).'/validationEngine.jquery.css" type="text/css"/>';
echo $content;

The first function (print_form_scripts) when called, will register a couple of scripts to the page,
The second function (print_form_styles) when called, will add an html line to the head content, a call for a css file, that is relevant for the form validation.

Now, all is left to do, is actual hooking of these functions to the wp_head action.

In order to do so, open your new page’s unique theme file (page-NNN.php) and add these lines, before the call for the get_header() function:
add_action('wp_print_scripts', 'print_form_scripts');
add_action('wp_head', 'print_form_styles');

Keep in mind, that these lines should be added to the file before the call for the theme’s header file (get_header()), as they are hooked to wp_head, which in its turn, is called from within the header file.

Having done that, you can refresh the page and check it’s html hitting “view source”, and see that indeed the calls to the requested js and css files are added to the head html, for this page only.

Customizing a Page on WordPress

It’s always recommended to be consistent with your site’s look and feel. However, there may be a time when a page calls for a unique look and feel. Be it you homepage, or a special landing page, or a complex form. For those cases there should be a way to customize a unique page without affecting other pages’ appearance, and indeed, there is. In fact, there are at least two.

WordPress has a theme hierarchy. Which means that whenever a page is loaded, the system detects its type, and calls for a ceratin template file from your theme directory. If that file is missing, WordPress will fall back to the next in line.

For page display, WordPress will look for a theme file called page.php, however it will look first for a file called page-NN.php, where NN be the pages id.

So if your special page’s ID is 44, create a file in your theme’s directory, called page-44.php, and use it to customize your page layout. Even better would be to save the page.php file as page-44.php. That way you already have a base that you can start work on.

You can also create a file named page-my-new-landing-page.php, where “my-new-landing-page” be your special page’s slug. Yes, before WordPress looks for a page-NN.php, it looks for a page-SLUG.php!

Read more about WordPress theme hierarchy here.

Using a theme file

Sometimes you need to customize not just one page, but a couple of pages. For example, a series of landing pages. In this case, you will be better off setting a special template file to rule them all.

First thing: Create a file in your theme directory, and give it a name. For instance: “landing_page.php”.

Open the file with your favorite text editor and add these lines:

* Template Name: Landing Page Them
* A custom page template for landing pages

The “Template Name” bit is the identifier of this theme.

Once this is done, go to the back office and create or edit a page. When the page is open for editing you will notice on the right hand side the “template” drop-down menu. From this menu you can now choose your new template for this page, and others.

What’s $(this)??

I am far from being a javascript Ninja. But I do try to catch up.
The first JS library I used to work with was Prototype + Scriptaculous. Unfortunately These are not maintained anymore. So I moved on to the next Buzz – Mootools.

I really like Mootools. It’s a great powerful library. Unfortunately, Mootools’ golden days seem to be over. The new king is now Jquery. The fact that all the big players – Yahoo, Google, Microsoft implement this library for all their projects makes it a safe bet and the immediate choice for any developer. So although Mootools is great and my own choice, me too, I should move on.

At start I found Jquery rather annoying. On one hand it’s easy enough to point to a DOM element using the same notation as being used on your stylesheet. On the other hand I now need to learn new references to all its attributes and remember to pass them as arguments in a function, instead of the original and intuitive assignment. Html(‘bla’) instead of innerHTML = ‘bla’, css() instead of style, etc.. On top of everything – what’s with the $(this)? How does it relates to ‘this’? This is mind boggling.

So here’s the deal, in a nutshell:

Whenever we call the Jquery function, or its alias $, with a jquery DOM selector as a parameter, we get in return an array of elements.

For instance, if we point to ‘.my_class’, i.e. pass it as a parameter to Jquery (), we get back an array that contains all the elements in the page that have the ‘my_class’ class.

And here’s the big thing: we can refer to the first member of this array as ‘this’.
$(this)[0] == this
That means, that if we point only to a unique element:
$(‘#my_unique_element’)[0] == this;
$(‘#my_unique_element’).html(‘new content!’);
Is as good as
$(‘#my_unique_element’)[0].innerHTML = ‘new content!’;

As this is a reference to an element within its own context, $(this) means we pass it as a parameter to the Jquery function.

When we are within the context of $(‘.my_elements’), ‘this’ is any element that has a ‘my_elements’ class, and $(this), is that same element being passed to the $(Jquery) function. That way we can apply all the Jquery magic on it.

Keeping this in mind may also help us making our code more efficient: As Jquery almost never throws error at selecting a none-existance dom element, we now have a way to manually test that it indeed exists before we go on trying to manipulate it, simply by checking the returned array length:

if ($(‘div.my_elements’).length) { … }
When it equals 0 – i.e – jQuery returned an empty array – no such element on the DOM, let’s move on!

Why Would Products Suddenly Disappear from my Homepage in Magento?

Paul Simon listed 50 ways to leave your lover. I am about to list at least 50 ways for Magento to give you a heart attack. The most recent one resulted in an urgent text message from my client: He added a new category – and – magic! Next thing he knows: the home page is empty.

I have already written about troubleshooting products not displayed in Magento’s front. However this case is a bit different: while there – the products where never displayed on the site – neither on new products page nor on category’s page, here – right at creation, they were displayed as expected. However, for some mysterious reason, they suddenly disapeared!

So I run again for help from Mr.Google. Go through the check list again. Here’s something I haven’t tried yet: re-indexing.

System => Manage Indices. All items are green as in ‘updated’. I decide to give them a shake anyway: I hit select all, then selected Reindex Data on the actions menu, then hit Submit. Tada! More magic! The products are back!

Here’s also a detailed explanation of what may cause this behavior and how to ‘ghostbust’ it

How to be Notified About New Orders in Magento

surprisingly enough (at least for me), you, as a store owner, are not notified by default about new orders on your store.

For really large stores with lots of activity, that may make sense. But if you run a small or medium size business you would probably prefer to be notified, especially if you make deliveries.

As with everything in Magento, it took me quite a while to figure out how that’s done. Nothing on it in the wiki, at least as far as i could see, very little about it with Google.

So here’s how it’s done (courtesy of Nik Chankov of Blog for web development):

  • Login to the admin area
  • System => Configuration => Sales => Sales Emails
  • In the Send Order Email Copy To field – fill in your/the admin’s email address
  • With the Send Order Email Copy Method drop down – select Separate Email.
  • That should do. Simple when you know how.
  • If you still don’t get anything – go check your spam filter. It’s always better to set an un-monitored email address for such purposes, as most mail servers will treat auto-mail messages as spam and quaranteen it.

Yet Another Simple Gallery Plugin for WordPress

I have been looking for a really simple gallery plugin that can use WordPress’ native Gallery features and jquery support, but couldn’t find any. My qualifications were simple: a row of thumbnails, a main photo, and a way to switch to another photo by clicking on its thumbnail. I didn’t want the featured image to be modal, like in a lightbox mode, but located in the same page as the thumbnails. Only thing resembling what I was looking for, was really hard to adapt, even in terms of css. I know there are millions of gallery plug-ins out there, so my search was probably not good enough, however – I ended up writing it from scratch.

It was registered today with WordPress.

This plugin is really simple. All you need to do is download and activate it. Then go ahead and create a new post with gallery for your photos. What happens next is that the photos are arranged in your new post like small thumbnails and a main image. Clicking on a thumbnail will switch the main image to the one related to the clicked thumbnail. Off-course, if you are as control freak as I am, and you definitely need to make a change – you can create a yasg.css file, save it under your theme folder, and change any css rule you feel like. These rules are to override the gallery’s default css rules. I can hardly imagine you’ll ever need more control than that.

The plugin was tested on WordPress 3.2.1

Please comment on this post, if any problem, bug, question or ideas for improvements.

Download the plugin now.