My *nix world

Inject JavaScript code WordPress

In my previous article I have proved the concept of injecting PHP code in a WordPress post/page.

WordPress is a very well written CMS driven by a plug-in architecture. If you want to insert some JavaScript code into a WP post/page you have few options:

  • you can create a WP child theme and then a custom page template where you could inject JavaScript code WordPress
  • you can write a plug-in that basically will parse the original page content and replace a JavaScript code block with a functional runtime JavaScript

Create a child theme

If you want to extend the functionalities of your WP default theme you might consider creating a new child theme which inherits all its parent functionalities. Activate and use the newly created child theme. You can define the child theme customizations (by writing and/or injecting some JavaScript code in header, footer, page content, etc) that will enhance the current theme user experience. Read more.

Create a custom page template

You can define a custom page template that you can use it later when you write a post. In this custom page template you embed the JavaScript code you need. It will run for each post that uses this custom page template. Read more.

Writing a plug-in

This is my favourite method although the injection of JavaScript code in your WP post can be achieved easily by using the two methods named earlier. The principle should be exactly the same, the only difference is that you wrap the whole thing/customization into a small package called Plug-in. There is a difference, though: it will work not only on the default website theme but also on all the themes that your website has (like the theme used to deliver the content to the mobile devices, etc).

To write a plug-in is as simple as saying "Hello". I'm not kidding, it really is!

Check this out:

<?php
/**
 * Plugin Name: Name Of The Plugin
 */

?>

This is the simplest WordPress plug-in ever. You only need to specify the "Plugin Name : <the name>" and that's it. Of course, it does nothing but at least you can understand the concept. If you want to learn more about writing plug-ins for WordPress then don't forget to read this.

The aim of a WP plug-in is to alter the way that the WP produces the content by default. What the WP developer did was to create an architecture that allows you to hook/inject your code just before/after various portion of their code. By doing that you have the chance to alter the post/page content just before WP does or just after it did.

How can we use this for inject JavaScript code WordPress?

Well, we write a function and inject it right before the WP sends/outputs the page content to the client. By doing this we have the chance to alter the default page content, also to filter the content delivered to the client. This behaviour was named (by WP developers) filter. We can write and add one or several filters that will actually filter portions (like the header, the footer, the page content, etc) of the web page.

The simplest filter ever could look like this:

function my_filter_function($content)
{
   return $the_content;
}

We wrote a filter that does nothing. But this was the idea, to be simple, to help you understand the concept. What it does? It receives the original content ($content variable) and delivers it as is (the unchanged $content).

So far your plug-in code looks like this:

<?php
/**
 * Plugin Name: Name Of The Plugin
 */
function my_filter_function($content)
{
  return $the_content;
}
?>

Don't hurry to use it, it will not work in this version. We are just one step away, though.

We could have hundred of various functions in this file so WP has no clue which one is some helper function and which one represents actually the filter that you want to use. To let WP know about your filter all you have to do is to add one line more in the plug-in file main code:

add_filter('the_content', 'my_filter_function');

While 'my_filter_function' refers our custom function that is supposed to filter the original page content, the 'the_content' is actually the WP predefined name of the hook/filter. If you use some filter name that only you (and your friends probably) know about it then nobody will use it because nobody has knowledge about its existence. So meanwhile stick to the predefined WP filter list, it is pretty large, you will see.

Anyway, how looks our final version of WP plug-in now?

<?php
/**
 * Plugin Name: Name Of The Plugin
 */

function my_filter_function($content)
{
  return $the_content;
}

add_filter('the_content', 'my_filter_function');
?>

Do you want to use it? If you do then please follow the steps below:

...and that's it!

Now, let's customize little bit this plug-in so that anytime when it finds in the page content a custom short code like:

[my_tag]

... JavaScript code goes here

[/my_tag]

it will inject that JavaScript code in the resulted HTML page (either in the footer, the body or the header) and will replace the original block of code with nothing (we don't want to see JavaScript code, do we?).

The steps to implement this are the following:

  • search the original content for all blocks that start and ends with our custom tag (i.e. [my_tag] and [/my_tag])
  • memorize any JavaScript block codes that we find in a variable
  • replace the entire block (including the tags) of that JavaScript code with nothing
  • return to WP the altered version of the page content (by stripping that block code)
  • finally, inject the stored JavaScript code either in the header, body or footer the scipt(s) code we've found

Search for our custom tag

We can simply use the regex pattern together with the JavaScript preg_match_all function:

global $java_script;
preg_match_all("/

my_tag

(.*?)

\/my_tag

/s", $content, $matches); foreach ($matches[1] as $javaScript_filter_key => $match) { $match = html_entity_decode($match); $match = preg_replace('@<[\/\!]*?[^<>]*?>@si', '', $match); $match = "<script>" . $match . "</script>"; .....

The regex pattern above will match all blocks that starts with [my_tag] followed by zero or more of any characters and which ends wit [/my_tag]. We should decode that HTML block because it certainly will be HTML encoded. In case we still find any HTML code enclosed within <some_tag> and </some_tag> we should discard that code because it would never run as a JavaScript code. Actually our JavaScript code will fail to evaluate if such HTML code is found.

Replace the block code with the result

  $content = str_replace($matches[0][$javascript_filter_key], "", $content);
  $java_script .= $match;

We don't want to output the original JavaScript code block. So in the original page content we replace that JavaScript block code with nothing. Moreover, we should memorize that JavaScript block because we are going to need it later when we inject it either in the header, body or footer.

Inject the JavaScript code

What we've done so far was to detect such JavaScript blocks, to memorize them in a global variable $java_script and to strip that block from the original page content. So we still have to inject that code sometime, somehow, somewhere.

What we do is to write another WordPress hook but this time an action hook. I am not going to explain all differences between filters and actions, you can find out more about it right here.

The hook's code is fairly simple:

function inject_javascript_shortcode() {
   global $java_script;
   echo $java_script;
}

It just output the global stored $java_script variable.

The complete functions code

function filter_javascript_shortcode($content)
{
  global $java_script;
  preg_match_all("/

javascript

(.*?)

\/javascript

/s", $content, $matches); foreach ($matches[1] as $javascript_filter_key => $match) { $match = html_entity_decode($match); $match = preg_replace('@<[\/\!]*?[^<>]*?>@si', '', $match); $match = "<script>" . $match . "</script>"; $content = str_replace($matches[0][$php_filter_key], "", $content); $java_script .= $match; } return $content; } function inject_javascript_shortcode() { global $java_script; echo $java_script; }

It encloses about 10 lines of code. Great, but we are not done yet. Nobody knows about our action hook so nobody will inject the JavaScript code nowhere. To let WP know about our action hook all we have to do is to add one line more in the plug-in file main code:

add_action('wp_footer', 'inject_javascript_shortcode');

As you can see this time I haven't used add_filter but add_action whose role is not to filter the content but to execute something. I want to execute "inject my JavaScript in the footer". Note that the action name 'wp_footer' is predefined in WordPress so stick to that name. I choose this particular action 'wp_footer' because I want to inject this JavaScript code in the footer part of the page. You could instead choose 'wp_header' or even the body, i.e. 'the_content'.

 

Your plug-in file will contain two functions and two hooks.

 

If you write a post/page and, among other things you wrote, you will write (at design time) the text below:

[my_tag]
document.write("<p>My First JavaScript</p>");
[/my_tag]

when the page will be interpreted by your browser at runtime it will output a paragraph like this:

My First JavaScript

Just as an example, I have used the technique described above in a page where I run a JavaScript code that uses Ajax to load asynchronously some diagrams. Just take a look.
If you will check the source of the mentioned page in the link above you will notice somewhere a JavaScript function called "loadImg". The whole code that is enclosed there was nothing less than a [my_tag] ... my JavaScript code [/my_tag] plain text in my post/page. So that block was transformed from plain text into a runnable JavaScript. Nice!

Conclusion

To inject a custom JavaScript code into your web WP pages you need to write a 20 lines of code plug-in that does the job. That simple is to inject JavaScript code WordPress web page.
[nolatex]

Now, if you think that this article was interesting don't forget to rate it. It shows me that you care and thus I will continue write about these things.

 
The following two tabs change content below.
Inject JavaScript code WordPress

Eugen Mihailescu

Founder/programmer/one-man-show at Cubique Software
Always looking to learn more about *nix world, about the fundamental concepts of math, physics, electronics. I am also passionate about programming, database and systems administration. 16+ yrs experience in software development, designing enterprise systems, IT support and troubleshooting.

Leave a Reply

Your email address will not be published. Required fields are marked *