You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Daniel M. Hendricks edited this page Oct 1, 2017
·
1 revision
ScriptObject can be used to inject JavaScript variables or CSS into the page head or write/enqueue external files.
Methods
injectCSS - Injects CSS into the page head.
injectJS - Injects JS into the page head.
enqueueCSS - Enqueue (and optionally update) CSS to an external file.
enqueueJS - Enqueue (and optionally update) JS to an external file.
writeCSS - Write CSS to an external file for later enqueueing.
writeJS - write JS to an external file for later enqueueing.
Arguments
script_dir (string) - The name of the directory to write external CSS/JS files to, located in uploads.
filename (string) - The name of the external CSS/JS file to write.
handle - (string) The CSS/JS handle to enqueue a script under.
variable_name (string) - A unique array variable name in which to store JavaScript values.
target (string|array) - Valid values: wp for the frontend, admin for WP Admin, or an array of both.
version (string|bool|null) -
A string version to enqueue the script as. Example: "1.1.0"
A boolean value - If true, the string representation of the file modified date/time will be passed (useful for discouraging caching in development/staging environments). If false or null, the WordPress version is passed.
Instantiation
$so = new \WordPress_ToolKit\ScriptObject( $args );
Enqueue and write (update) JavaScript to file uploads/my_plugin/dynamic.js:
$args = array(
'script_dir' => 'my_plugin',
'filename' => 'dynamic.js',
'handle' => 'my-plugin-js',
'variable_name' => 'my_plugin_settings',
'target' => ['wp', 'admin'], // Enqueue on frontend and WP Admin
'version' => true // Set version to file modified date
);
$values = array(
'my_site_name' => 'Another WordPress Site',
'some_var' => true,
'my_columns' => 4
);
$js = new \WordPress_ToolKit\ScriptObject( $values, true ); // Omit "true" to enqueue only
$js->injectJS( $args );
Using JavaScript Values
When you inject/enqueue JavaScript values, they are stored as an array named variable_name. You may reference them in your JavaScripts like this (using the example above):
$( '#selector' ).html( my_plugin_settings['my_site_name'] );
if( my_plugin_settings['my_columns'] > 2 ) {
// Do some magic
}