Run JavaScript from PHP in a WordPress Plugin

When you write a WordPress plugin, PHP mixed with HTML produces what the user sees. Often some JavaScript is needed as well — to build a dynamic element, set up a variable, or run an animation.

Including JavaScript with a plugin

The straightforward way is to ship a .js file with the plugin and register it with wp_enqueue_script. You can then mix in inline JavaScript that PHP generates as it goes. Suppose you want to pass a variable to a button’s onclick handler:

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>';
$output .= "n".'</div>';
echo $output;

JavaScript file

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

my_initialize is called immediately after the button with id my_button is created, and gives it an onclick handler that shows the $random_id value.

Why that call can fail

The catch is that my_initialize lives in a JavaScript file loaded alongside every other script and stylesheet on the page, and there is no guarantee it has arrived by the time the inline call runs. Depending on the theme and on the other plugins in play, the file may load after the PHP output has been printed — and the function will not exist when it is called.

Running it after the page has loaded

The fix is to call it once every element on the page is in place, using the document’s onload event:

...
$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>';
...

That implements onload properly: the action in $handler runs after the page has loaded, alongside any other onload actions rather than displacing them. It is also a cross-browser implementation — the last two branches cover browsers with no addEventListener, though in that case only one onload action can be registered.

On a site that only has to support current browsers, the first branch is all you need, and wp_add_inline_script is a tidier way to attach the inline call to the enqueued file in the first place.

If you have questions, please contact us.

The Iptanus team

Did this solve your problem?

Ask a question

Answered by Iptanus, usually within a working day.

Ask a question

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

Scroll to Top