Print-Clearly

Browse Site

Registering / Unregistering WordPress Scripts in the Header

The background behind this one is that I needed to alter the JavaScript filenames used within a plugin, font-resizer (which I would heartily recommend) in order to prevent an http 406 error being thrown which in turn was breaking all of the JQuery on my site. Having altered the filenames to avoid the error, I then needed to change the references in the code.

I’m not against changing someone else’s code in a plugin but I’m mindful of the portability of a site and, should anything go wrong, it’s a huge amount easier to change my code than it is someone else’s. I went through the plugin and found the following code, which told me how the JavaScript files were being pulled into the site:

function fontResizer_sortDependencys()
{
        $font_resizer_path = WP_PLUGIN_URL.'/font-resizer/js/';
        wp_register_script('fontResizer', $font_resizer_path.'jquery.fontsize.js');
        wp_register_script('fontResizerCookie', $font_resizer_path.'jquery.cookie.js');
        wp_register_script('fontResizerPlugin', $font_resizer_path.'main.js');
        wp_enqueue_script('jquery');
        wp_enqueue_script('fontResizerCookie');
        wp_enqueue_script('fontResizer');
        wp_enqueue_script('fontResizerPlugin');
}

(font-risizer.php, line 87)

The Fix

All I now needed to do now was reverse this in the theme of my site using the following WordPress functions:

Script Adding Script Removing
wp_register_script() wp_deregister_script()
wp_enqueue_script() wp_dequeue_script()

 

So the following code appeared in the header.php of the theme, before wp_head() (I have no idea whether the order is important or not, but it seemed logical to remove it from the queue prior to unregistering it):

wp_dequeue_script('fontResizerCookie');
wp_dequeue_script('fontResizer');
wp_dequeue_script('fontResizerPlugin');

wp_deregister_script('fontResizer', $font_resizer_path.'jquery.fontsize.js');
wp_deregister_script('fontResizerCookie', $font_resizer_path.'jquery.cookie.js');
wp_deregister_script('fontResizerPlugin', $font_resizer_path.'main.js');

At this point I simply hard-coded the usual JavaScript source into my site’s header, alongside my theme’s existing JavaScript source:

<script src=<?php echo $font_resizer_path; ?>.'jqueryfontsize.js'"></script>

Although I could, of course, have stayed with the WordPress hooks and registered the new paths for the plugin instead:

wp_register_script('fontResizer', $font_resizer_path.'jqueryfontsize.js');
wp_register_script('fontResizerCookie', $font_resizer_path.'jquerycookie.js');
This entry was posted in Blog, Blogging, php, Web, Websites, WordPress.

Comments are closed.