vastneed.blogg.se

Wordpress enqueue script example
Wordpress enqueue script example











wordpress enqueue script example

Wp_enqueue_style( 'wpa-main-css', get_theme_file_uri( 'dist/styles/main.css' ),, filemtime( get_theme_file_path( 'dist/styles/main.css' ) ) ) There’s actually almost identical function to wp_enqueue_script() called wp_enqueue_style() that allows you to enqueue css files. Wp_enqueue_script( 'wpa-main-js', get_theme_file_uri( 'dist/scripts/main.js' ),, filemtime( get_theme_file_path( 'dist/scripts/main.js' ) ), true ) Īdd_action( 'wp_enqueue_scripts', 'wpa_enqueue_scripts', 100 ) Use wp_enqueue_style() for css files Luckily it’s pretty easy to bust a cache with the timestamp of the js file: get_theme_file_uri( 'dist/scripts/first.js' ),, null, true ) Or you can enqueue a file with a handle 'first' and then use it as a dependency for your second file called 'second' like this: wordpress enqueue script example

The most interesting parts in that wp_enqueue_script() call is the first parameter ( 'wpa-main-js') and the last parameter ( true). You can use the admin_enqueue_scripts hook if you would like to enqueue a script into wp-admin. You can use wp_localize_script to pass data from PHP to JavaScript (see here for more information)Īnd take a note that we’re using the wp_enqueue_scripts hook here, which loads the script into your theme.You can set dependencies for the scripts you load, so for example you could add jquery as a dependency for your main.js (not covered in this post).The main benefits for using wp_enqueue_script() are: Wp_enqueue_script() works as an additional layer for these wp_head and wp_footerfilters. Would echo  to the place where you call the wp_head()function.Īnd you could definitely do something like this: ' Īdd_action( 'wp_footer', 'main_js_to_wp_footer', 100 ) īut there’s still a better way to enqueue scripts into your WordPress theme. So for an example this: "Īdd_action( 'wp_head', 'hello_world_comment', 100 ) Wp_head() and wp_footer() are basically places where you can echo things through wp_head and wp_footer hooks. They’re used placed into your header.php and footer.php in a way that those files combined would look like this: To understand fully how wp_enqueue_script() works we should take a look at the wp_head() and wp_footer() functions. In this article I’m going to show you how, why and when you should use wp_enqueue_script() to load your JavaScript files. While this obviously works, I later discovered that there is a better way to enqueue scripts built in WordPress core. If ( is_page_template( 'my-page-template.In the early days in my career as a WordPress dev I used to load my JavaScript files like this: /wp-conteht/themename/dist/main.js">













Wordpress enqueue script example