One of the most frustrating items I’ve come across recently is that alot of WordPress plugins include their own version of jQuery or similar JavaScript library. Please Stop!!!!

What you may not realize is that WordPress comes bundled with the jQuery library and to boot they provide a simple method to not only include it in your website but to ensure that it only gets included once. Please familiarize yourself with the wp_enqueue_script function as it will make your plugins cleaner and help to mitigate conflicts with other plugins and templates.

To include jQuery, Scriptaculous, or similar libraries is a simple 2 step process.

  1. Register a method for the init hook
    This is necessary as the wp_enqueue_script should be called upon the init stage of WordPress execution.
    add_action('init', 'plugin_init');
  2. Enqueue the jQuery library
    function plugin_init() {
        wp_enqueue_script('jquery');
    }

There you have it you have now included jQuery into the website that uses your plugin.

, , , , , ,

In Dynamic websites we often find that we need to modify page content on the fly based on user actions. A common example of this is allowing the user to add additional input boxes for configurations or attachments. I personally like to contain such input as a new row in a table. To accomplish this I utilize the jQuery library for JavaScript.

For illustration lets assume we have the following table in our page:

<table id="exampleTable1">
<tr>
    <th>City</th><th>State</th>
</tr>
<tr>
    <td>Rochester</td><td>New York</td>
</tr>
<tr>
    <td>Boston</td><td>Massachusetts</td>
</tr>
</table>

In this example the approach to adding more columns is very straightforward as we can utilize jQuery’s child and last selectors with the after modifier to add a new table row.

var newRow = '<tr><td>Albany</td><td>New York</td></tr>';
$('#exampleTable1 tr:last').after(newRow);

These 2 lines of JavaScript create the new row as a string then utilizes jQuery to get the last row of the table and append the new row after it, adding this row to the end of our table.

If a table contains a tfoot element with rows then the above will insert a row in the footer, A modification that can be done is to obtain the tbody element of the table and append the new row.

$('#exampleTable1 tbody').append(newRow);

That is all there is to it simply define your new row as a string then utilize jQuery to identify where you would like that row added to the DOM.

, , , ,