Including dynamically generated, locally hosted JavaScript using a plugin
-
Hi,
I wish to enqueue a javascript fragment using a plugin, but part of the javascript is dynamic, e.g.
myJavaScriptFunction('DYNAMIC_PARAMETER');
I would like to retrieve DYNAMIC_PARAMETER from a plugin setting and insert it into the JavaScript function call.
I thought I’d be able to use a PHP file to generate the JavaScript file dynamically, using the query string to append the wordpress plugin setting, e.g.
add_action('wp_enqueue_scripts', 'get_js'); function get_js() { $dynamic_parameter = get_option('dynamic_parameter'); wp_register_script('dynamic_js', plugins_url("/js/dynamic_js.php?dynamicParameter={$dynamicParameter}", __FILE__)); wp_enqueue_script('dynamic_js'); }
Where js/dynamic_js.php is in my plugin directory and contains the following.
<?php header("content-type: application/x-javascript"); if (array_key_exists('target', $_REQUEST)) { $dynamicParameter = $_REQUEST['dynamicParameter']; } else { $dynamicParameter = ''; } $script = <<<EOD /* <![CDATA[ */ function myJavaScriptFunction('$dynamicParameter'); /* ]]> */ EOD; echo $script;
Unfortunately WordPress says it can’t find the file when I request it. Is there a way I can include dynamically generated JavaScript using a WordPress plugin?
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘Including dynamically generated, locally hosted JavaScript using a plugin’ is closed to new replies.