Add JQuery App using WordPress Custom Page Template

If you have developed a JQuery or JavaScript web application and want to run the application on a WordPress page, then this post is for you. For ease of understanding, I will be using a JQuery application snippet that counts the number of words in a textarea. For the purpose of this post, I will be using the BLANK THEME by Chris Coyier to demonstrate this.

[box type=”info” style=”rounded” icon=”info”]Note: Care should be taken when making changes to your Active WordPress theme. So take a backup of your theme’s folder. Also you need an FTP client application to connect to your WordPress directory[/box]

Step 1: Create your Application Page Template

– Connect to your WordPress directory, navigate down to “/wp-content/themes/BLANK-Theme (your theme here)/“. Copy and paste your .js file into the JS directory (‘wordcount-script.js‘)

jquery-01

[box type=”info” style=”rounded” icon=”info”]Note: The jQuery library included with WordPress loads in “no conflict” mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In “no-confict” mode, the $ shortcut is not available and the longer jQuery is used. So for your script to run, change the $ sign to jQuery as shown below[/box]

jquery-05

– Do same for your CSS file. Give it a name ‘wordcount-style.css‘ and place the file in the CSS folder in your theme’s directory

jquery-02

– Under the theme’s folder, create a new php file (wordcount.php) and add the following code snippet

[code lang=”php”]

<?php

/**

  • Template Name: WordCount

*/

//

function wordcount_enqueue_scripts() {

$file = ‘/js/wordcount-script.js’;

wp_enqueue_script(

‘wordcount-script’,

get_stylesheet_directory_uri() . $file,

array( ‘jquery’ ),

filemtime( get_stylesheet_directory() . $file ),

TRUE

);

$file = ‘/css/wordcount-style.css’;

wp_enqueue_style(

‘wordcount-style’,

get_stylesheet_directory_uri() . $file,

array(),

filemtime( get_stylesheet_directory() . $file )

);

} // function wordcount_enqueue_scripts

add_action( ‘wp_enqueue_scripts’, ‘wordcount_enqueue_scripts’ );

?>

<?php get_header(); ?>

// Enter your HTML code here

Total number of words:

<?php get_footer(); ?>

[/code]

Quick overview of each section of the above code below. Refer to article [button link=”http://codex.wordpress.org/Function_Reference/wp_enqueue_script” size=”mini” style=”info” color=”primary” class=”sys_btn”]WP Enqueue Script[/button] for more information

jquery-03

Step 2: Create a new WordPress page

– Add a new WordPress page and give it a name. Under Template, select the newly created template name and publish

jquery-04

– Preview the new custom page and your application should now be loaded

jquery-06

Hope this was easy to follow. Feel free to comment if you run into any issues 🙂

 
comments powered by Disqus