![]() ![]() And if you want to include a JavaScript file on only some pages on your WordPress site, read our guide to conditionally enqueueing JavaScript files.If you want to understand better how plugin_dir_url() works and what function works equivalently for WordPress themes, check out at our article on linking to theme and plugin resources.If you want to know more detail about enqueueing both JavaScript files and CSS stylesheets in WordPress, read our full-length article on the topic.Plugin_dir_url(_FILE_).'quick-guide.js'Īnd that’s how to add a JavaScript file in WordPress! Since it can be helpful to see all the code at once, here’s the final version of our custom plugin’s code: add_action('wp_enqueue_scripts', 'qg_enqueue') The WordPress hook for enqueueing scripts and stylesheets meant to be used for your admin dashboard is called adminenqueuescripts. How To Use wp_enqueue_script() to Add JavaScript to Each Page on Your WordPress Site: Full Code Example '/js/example.js' This is the reference to your theme directory and the javascript file. I just posted this wpenqueuescript ( handle, src, deps, ver, infooter ) to show you how the action works. (If you’re working in a theme, get_stylesheet_directory_uri() is a similarly helpful function for getting to the root of the running theme.) Then the last piece, quick-guide.js, is where you need to go (folder and filename) relative to the root directory you established with plugin_dir_url(). Put it in wp-content/themes/your-theme/js/. If you’re working in a plugin, as in our example, using plugin_dir_url() with the magic _FILE_ constant is the easiest and most common way to get to the plugin’s root folder. ![]() Your wp_enqueue_script() call will be specific to your JavaScript file’s “shorthand name,” file location, and filename.Wp_enqueue_script('qgjs', plugin_dir_url(_FILE_).'quick-guide.js'). Add a body to the function which actually registers and enqueues your script, using wp_enqueue_script().Create that function qg_enqueue() with a basic function qg_enqueue() expression.Don’t save yet, because saving without having written the qg_enqueue() function itself will temporarily “break” your site. ![]() Our example above would load the scripts in the footer if we modify it slightly.
0 Comments
Leave a Reply. |