When developing a WordPress plugin, PHP code, mixed with HTML, is used to generate the visual representation of it to the user. Besides PHP and HTML, it is sometimes necessary to run some Javascript code as well, in order to generate dynamic elements or initialize variables or generate some complex animations.

One easy way to run Javascript code is to create a Javascript file (.js) and include it with the plugin, using the wp_enqueue_script function. You can also mix it with inline Javascript code generated dynamically using PHP. For instance suppose that you want to pass a variable to a button onclick function:

PHP file

$random_id = "12232dfd.5456";
$output = "\n".'<div>';
$output = "\n".'<button id="my_button">Press me</button>';
$output = "\n".'<script type="text/javascript">my_initialize("'.$random_id.'");</script>';
echo $output;

Javascript file

function my_initialize( id ) {
  document.getElementById("my_button").onclick = function() { alert(id); };

The Javascript function my_initialize will be called right after the creation of button with id my_button and will assign to it an onclick event showing the $random_id variable when pressed. However, function my_initialize is included inside a Javascript file, loaded together with all the other files of the page (script files, style files etc) and it is not sure that this function will be available by the time it is called by the php script. Depending on several factors, such as the theme of the website or other plugins loaded, the Javascript file containing my_initialize function may be loaded after the execution of the PHP file, so the function will not be available when called by the php script.

In order to resolve this kind of issues, the right way to call my_initialize function is after all page elements have been loaded, so that it is certain that it is available. To do this, onload event of document object will be used. So, the right way to call my_initialize function is the following:

$handler = function() { my_initialize("'.$random_id.'"); };
$output = "\n".'<script type="text/javascript">if (window.addEventListener) { window.addEventListener("load", '.$handler.', false); } else if (window.attachEvent) { window.attachEvent("onload", '.$handler.'); } else { window["onload"] = '.$handler.'; };</script>';

The above code correctly implements onload event, so that the action defined in $handler variable is executed after the page has been loaded, together with any other onload actions. It is also a cross-browser implementation and it will work in old browsers as well that do not support addEventListener or attachEvent methods (at this case there will be only one onload action).

Run Javascript Scripts with PHP

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.