Enqueue script wordpress6/18/2023 ![]() ![]() 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') How To Use wp_enqueue_script() to Add JavaScript to Each Page on Your WordPress Site: Full Code Example (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(). 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. Write the line add_action('wp_enqueue_scripts', 'qg_enqueue'). ![]() (If you’re trying to do this for a theme, you’d put the following code in your functions.php file.) If not, check out our primer on making a WordPress plugin. You’re going to be writing PHP, and we’re going to assume you’ve got a custom plugin set up to do this in.And here’s the text version of that same guide for how to use wp_enqueue_script() in WordPress… How To Use wp_enqueue_script() to Add JavaScript to Each Page on Your WordPress Site Oftentimes, you only want to enqueue your scripts and styles files in the WordPress template or theme, if that shortcode is getting used by the active page. ![]()
0 Comments
Leave a Reply. |