Proper Way To Include Js Files With Sage Wordpress Theme
Solution 1:
Including custom script (not installed via bower package manager)
You can use scripts/**/*
glob pattern. This will bundle all scripts that are inside assets/scripts/
directory into dist/scripts/main.js
file.
Edit your assets/manifest.json
like this:
{
"dependencies": {
"main.js": {
"vendor": [
// Your external libs that are not available via bower
]
"files": [
"scripts/**/*",
"scripts/main.js"
],
"main": true
},
.
.
.
vendor
- property paths are relative to your project rootfiles
- property is relative to yourassets
folder
For more info visit some examples.
Installing & including bower dependency
For example, let's install carousel Slick library.
Install library via bower
bower install --save slick-carousel
Next you need to tell which files do you need from installed package. So you need add paths of those files to
overrides
section ofbower.json
file.
NOTE: Paths are relative to /bower_components/<package_name>
.
"slick-carousel": {
"main": [
"./slick/slick.min.js",
"./slick/slick.css"
]
}
Now library will be part of compiled dist/scripts/main.js file.
Solution 2:
You need to add code to functions.php file. You will see there sage_sripts or similar function and within that function you will need to add wp_enqueue_script
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
Here is a sample:
/**
* Enqueue scripts and styles.
*/functionsage_scripts() {
$scripts_version = 1;
wp_enqueue_style( 'sage-style', get_stylesheet_uri() );
wp_enqueue_script( 'yourscript', get_template_directory_uri() . '/js/yourscript.js', array(), '1', true );
}
add_action( 'wp_enqueue_scripts', 'sage_scripts' );
Solution 3:
I haven't used this particular theme, but most likely there is a "custom javascript" box where you can insert your javascript. If you prefer to keep your javascript in files as opposed to copy-pasted into your theme, the answer is a bit more complicated.
I appreciate the way the Genesis Framework does it. Instead of a box for javascript they give a box for inserting any content you want (meta tags, styles, scripts) into the head of the theme.
You could also load a file through your theme's functions.php using wp_enqueue_script(). The problem here is that you can no longer (easily) update your theme, because the process would overwrite the changes to the file. You do not want to miss a single update for security reasons.
That's why I recommend a solution like this - a quick and easy plugin for inserting script files into the document. You get the files into your theme, and you no one can accidently overwrite or delete your changes later.
Post a Comment for "Proper Way To Include Js Files With Sage Wordpress Theme"