Nel caso si abbia la necessità di accodare dei file js o css in wordpress bisogna aggiungere del codice nel file functions.php tipo quello che segue:
// attivo la mia funzione con add_action() di WordPress add_action( 'wp_enqueue_scripts', 'iw_vegas' );
/* funzione personalizzata per l'accodamento di:
1 file css
1 file js
inoltre voglio passare come parametro la path del tema utilizato e per fare questo utilizzo la funzione di WordPress wp_localize_script()
*/
function iw_vegas() {
// get_stylesheet_directory_uri() restituisce la path del tema utilizzato
wp_register_style( 'vegas-css', get_stylesheet_directory_uri ().'/custom/vegas.css' );
wp_register_script( 'vegas-js', get_stylesheet_directory_uri ().'/custom/vegas.js' );
wp_register_script( 'iw-js', get_stylesheet_directory_uri ().'/custom/iwjs.js' );
if(is_front_page()){
wp_enqueue_style( 'vegas-css' );
wp_enqueue_script( 'vegas', get_stylesheet_directory_uri().'/custom/vegas.js', array( 'vegas-js','iw-js'), '1.0', true );
wp_localize_script('vegas', 'myScript', array(
'tema_path' => get_template_directory_uri()
));
}
}
Vediamo ad esempio il file js caricato come utilizza il parametro passatogli
var iwjs = new Iwjs();
document.addEventListener('DOMContentLoaded', function(){
iwjs.init();
});
function Iwjs(){
this.main = document.getElementById('iw-slider');
this.container = jQuery('#iw-slider-items');
this.numslide = 6;
this.init = function(){
this.iwslider('init');
};
this.iwslider = function(){
if(p1=='init'){
let slides = [];
for(let i=0; i < this.numslide; i++){
let x = i + 1;
slides.push({src: myScript.tema_path + '-child/custom/slide/slide-' + x + '.jpg' });
}
jQuery('#iw-slider-items').vegas({
slides: slides,
transition: 'blur',
delay: 6000,
autoplay: true,
overlay: false,
timer: false
});
}
};
}