The free-as-in-beer nature of WordPress and many of its themes and plugins is fantastic for experimenting with your site’s design without breaking the bank. However, with such a wide array of options available from so many sources, it’s inevitable that bugs will appear – sometimes when you least expect it – and support isn’t always available. This is where the free-as-in-speech aspect of WordPress and its add-ons shines. The ability to quickly identify and fix bugs in open-source code saves time and effort that might otherwise be spent reporting bugs and waiting for them to be fixed, or having to implement an entirely new theme or plugin if a fix isn’t in the works. The following is a case-study in fixing a WordPress theme.
Or so we thought. Plugins began working again, but the Nivo Slider that Boldy includes by default on the home page failed to load any images. The slider had been working before adding the call to wp_head because everything it required was hard-coded by Boldy in home.php. This meant that a plugin was loading something in wp_head that was causing a conflict with the slider.
The first step was to get an idea of what was being generated by wp_head. By wrapping the call to wp_head in HTML comments, we could simply reload the home page and use the browser’s tool to view the source:
<!-- *** BEGIN wp_head() *** --><?php wp_head(); ?><!-- *** END wp_head() *** -->
Initialization of jQuery in a WordPress theme or plugin must be done using the PHP function wp_enqueue_script in order to avoid conflicts. Because Boldy initialized jQuery outside of this function, WordPress has no idea that jQuery has already been loaded, and proceeds to load it again if it’s required by a plugin. The reason this is a problem is that WordPress loads jQuery in no-conflict mode. The usual $ shortcut that jQuery users are accustomed to is disabled to avoid conflicts with other libraries that implement $. For example, instead of:
If jQuery is initialized improperly, the $ shortcut may work, but only until WordPress properly reinitializes jQuery in wp_head using no-conflict mode. At this point, the $ shortcut is disabled, and any code written using it won’t work. This is precisely why the home page slider stops working. The code to initialize the slider occurs after wp_head, and uses the $ shortcut.
At this point, we have identified the main problems with the Boldy theme. In a future post, we will explore the proper use of wp_enqueue_script and how to deal with jQuery code that is unaware of no-conflict mode.