Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coppa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Come aggiungere correttamente JavaScript e stili in WordPress

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Volete imparare ad aggiungere correttamente JavaScript e fogli di stile CSS in WordPress?

Molti utenti fai-da-te spesso commettono l’errore di chiamare direttamente gli script e i fogli di stile nei plugin e nei temi.

In questo articolo vi mostreremo come aggiungere correttamente JavaScript e fogli di stile in WordPress. Questo sarà particolarmente utile per coloro che stanno iniziando a imparare lo sviluppo di temi e plugin per WordPress.

Properly adding JavaScripts and styles in WordPress

Errori comuni nell’aggiunta di script e fogli di stile in WordPress

Molti nuovi sviluppatori di plugin e temi per WordPress commettono l’errore di aggiungere direttamente i loro script o CSS inline nei loro plugin e temi.

Alcuni usano erroneamente la funzione wp_head per caricare gli script e i fogli di stile.

<?php
add_action('wp_head', 'wpb_bad_script');
function wpb_bad_script() {
echo 'jQuery goes here';
}
?>

Anche se il codice precedente può sembrare più semplice, è il modo sbagliato di aggiungere script in WordPress e porta a maggiori conflitti in futuro.

Ad esempio, se caricate jQuery manualmente e un altro plugin carica jQuery con il metodo corretto, jQuery viene caricato due volte. Se viene caricato su ogni pagina, ciò influisce negativamente sulla velocità e sulle prestazioni di WordPress.

È anche possibile che le due versioni siano diverse, il che può causare conflitti.

Detto questo, vediamo il modo corretto di aggiungere script e fogli di stile.

Perché inserire gli script e gli stili in WordPress?

WordPress ha una forte comunità di sviluppatori. Migliaia di persone da tutto il mondo sviluppano temi e plugin per WordPress.

Per assicurarsi che tutto funzioni correttamente e che nessuno pesti i piedi agli altri, WordPress dispone di un sistema di enqueuing. Questo sistema fornisce un modo programmabile per caricare JavaScript e fogli di stile CSS.

Utilizzando le funzioni wp_enqueue_script e wp_enqueue_style, si indica a WordPress quando caricare un file, dove caricarlo e quali sono le sue dipendenze.

Questo sistema consente inoltre agli sviluppatori di utilizzare le librerie JavaScript integrate in WordPress, anziché caricare più volte lo stesso script di terze parti. Questo riduce il tempo di caricamento delle pagine e aiuta a evitare conflitti con altri temi e plugin.

Come inserire correttamente gli script in WordPress?

Caricare correttamente gli script in WordPress è molto semplice. Di seguito è riportato un esempio di codice da incollare nel file dei plugin, nel file functions.php del tema o in un plugin di snippets di codice per caricare correttamente gli script in WordPress.

?php
function wpb_adding_scripts() {
 
wp_register_script('my_amazing_script', plugins_url('amazing_script.js', __FILE__), array('jquery'),'1.1', true);
 
wp_enqueue_script('my_amazing_script');
}
  
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
?>

Spiegazione:

Abbiamo iniziato registrando il nostro script tramite la funzione wp_register_script(). Questa funzione accetta 5 parametri:

  • $handle – L’handle è il nome univoco dello script. Il nostro si chiama “my_amazing_script”.
  • $src – src è la posizione dello script. Utilizziamo la funzione plugins_url per ottenere l’URL corretto della cartella dei plugin. Una volta che WordPress l’avrà trovata, cercherà il nostro file amazing_script.js in quella cartella.
  • $deps – deps sta per dipendenza. Poiché il nostro script utilizza jQuery, abbiamo aggiunto jQuery nell’area delle dipendenze. WordPress caricherà automaticamente jQuery se non è già stato caricato sul sito.
  • $ver – È il numero di versione del nostro script. Questo parametro non è obbligatorio.
  • $in_footer – Vogliamo caricare il nostro script nel piè di pagina, quindi abbiamo impostato il valore a true. Se si vuole caricare lo script nell’intestazione, si deve impostare il valore false.

Dopo aver fornito tutti i parametri in wp_register_script, possiamo semplicemente chiamare lo script in wp_enqueue_script(), che fa accadere tutto.

L’ultimo passo è usare il gancio dell’azione wp_enqueue_scripts per caricare effettivamente lo script. Poiché si tratta di un codice di esempio, lo abbiamo aggiunto proprio sotto tutto il resto.

Se si aggiunge questo al proprio tema o plugin, è possibile posizionare questo gancio d’azione dove lo script è effettivamente richiesto. Ciò consente di ridurre l’occupazione di memoria del plugin.

Ora qualcuno potrebbe chiedersi perché fare un passo in più per registrare lo script e poi metterlo in attesa? In questo modo, gli altri proprietari di siti possono cancellare lo script senza modificare il codice principale del plugin.

Inserire correttamente gli stili in WordPress

Proprio come per gli script, è possibile mettere in coda i fogli di stile. Si veda l’esempio seguente:

<?php
function wpb_adding_styles() {
wp_register_style('my_stylesheet', plugins_url('my-stylesheet.css', __FILE__));
wp_enqueue_style('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );  
?>

Invece di usare wp_enqueue_script, ora usiamo wp_enqueue_style per aggiungere il nostro foglio di stile.

Si noti che abbiamo usato l’hook dell’azione wp_enqueue_scripts sia per gli stili che per gli script. Nonostante il nome, questa funzione funziona per entrambi.

Negli esempi precedenti, abbiamo usato la funzione plugins_url per puntare alla posizione dello script o dello stile che volevamo mettere in coda.

Tuttavia, se si utilizza la funzione enqueue scripts nel tema, è sufficiente utilizzare get_template_directory_uri(). Se si lavora con un tema figlio, utilizzare get_stylesheet_directory_uri().

Di seguito è riportato un esempio di codice:

<?php
  
function wpb_adding_scripts() {
wp_register_script('my_amazing_script', get_template_directory_uri() . '/js/amazing_script.js', array('jquery'),'1.1', true);
wp_enqueue_script('my_amazing_script');
}
  
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
?>

Speriamo che questo articolo vi abbia aiutato a imparare come aggiungere correttamente JavaScript e stili in WordPress. Potreste anche voler studiare il codice sorgente dei principali plugin di WordPress per avere alcuni esempi reali di codice o consultare la nostra guida su come aggiungere facilmente JavaScript nei post o nelle pagine di WordPress.

Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

36 commentiLascia una risposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Jean-Michel says

    Hi there,
    I followed what is said here but now I get an empty white page on my web site. Could someone give me a hint ?
    Thanks

  3. Zaved Hossain says

    This is nice, though my usual practice is to add wp_enqueue_script/style in a single line without registering. Coders need to be careful about the parameters, perhaps a little explanation of that would be helpful. For example, the different versions of jquery (your jquery script may require different version than the wordpress’) and where to add it (header or footer which is determined by the true/false parameter). The jquery script needs to be added in the header, (hence a ‘false’ needs to be passed as the param value), otherwise it may not work.

  4. Hansjörg Leichsenring says

    There are often a lot of style.css.
    How can I ensure the correct load-order with enque and make sure, that the child css is loaded last?

    Cheers from Germany
    Hansjörg

  5. Carlos Araya says

    How do I pass empty parameter to register_script? I want to make sure that they script is loaded at the bottom of the page but can’t find information whether this is the default behavior or not

    • Kerry Beeher says

      Bonjour,

      Thank you for your excellente resource. Merci !!!

      I am little novice and just begin my journey to learn PHP and how WordPress use wp_enqueue_script and wp_register_script to add JavaScript and CSS.

      I use this free plugin called Easy Code Manager to help run through your exemples:
      however I am not sure if this is right plugin to use.

      I read before that it is not the best idea to modifier code in functions.php so I wonder if this is ok to do?

      Will it not get change on a theme update?
      Sorry for question, I still learn WordPress.

      Merci,
      Kerry

  6. Vaibhav Bansal says

    I want to add an Amazon Ad
    I tried to add it in text widget, but it shows blank.
    Below is the code-

    This is my site-
    Help me. How do I add js on my site?

  7. pradyumna says

    i have inserted a javascript using this plugin but now i have to remove it, i have tried uninstalling and deactivating the plugin but the javascript still executes

  8. Vijay.Rajpal says

    Hello Sir,
    I am using esteem theme and I wanted to add some javascripts functionality to my website like lightbox. I have created a child theme and the code are as follows. in the functions.php.

    and I am getting an error:-Parse error: syntax error, unexpected '{' in E:\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-content\themes\esteem-child\functions.php on line 18
    Please Help I am using sublime as my text editor.
    Please Help!!!!!

  9. Pramod says

    hello…..
    i m adding .js file in js directory of wordpress and gives its reference of it in funcation.php
    but its not working

    wp_enqueue_script( ‘any-navigation’, get_template_directory_uri() . ‘/js/menu.js’);

  10. Bobbie says

    Thanks so much! I’ve been trying to add a custom .js file but this is the first explanation that the register_script was needed.

  11. colkav says

    Hey, great tutorial. I’m having an issue adding a Google Analytics related javascript, as described here:
    I’ve put the script in my child theme’s ‘js’ folder (having first stripped the html from the code).

    When i load up the page I keep getting the error :

    ReferenceError: Can’t find variable: ga
    (anonymous function)myscript.js:6

    …and it just dawned on me that maybe I need to add ‘analytics.js’ as a dependency!

    Does that sounds right? And if so, how would I add analytics as a dependency for my script? I’ve tried experimenting here to no avail :(

  12. xavi says

    Hi.
    thanks for this amazing post tutorial! But when you say “where to upload the script” you just can define head or footer (in all entire webpages!)? Could you define an especific page to load it? I just need it in one. Thanks for advance and keep working! Cheers.

  13. Skye Barcus says

    I am a total novice at js but do know html. I want to put this on a wordpress page:

    Basically, it’s a widget to join a GoToMeeting. This works if you just throw it into the body of an html page, but in WordPress, it gets supressed.
    Can you give me a “For Dummies” version of how to make this work?

  14. Dejan says

    I really like you site it is full of useful tips, however looks like you are not doing it “Properly” for CSS enqueue even though your title say that way :=) The right way would be :

    wp_register_style( ‘my-css-style’, get_template_directory_uri() . ‘/css/style.css’, array(), ‘1.0’, ‘all’ );
    wp_enqueue_style( ‘my-css-style’ );

    Keep up the good work… Cheers!

  15. Adrian Zumbrunnen says

    Thanks for the effort you put into this. It just feels wrong to have wp_enque_script for loading stylesheets. WordPress could eventually spit out script instead of the stylehseet syntax for it.

    Do you really embed that way?

    • WPBeginner Support says

      This tutorial shows how to load JavaScript and stylesheet files for your themes or plugins in WordPress. If by Embed you meant how we display code in articles, then we use Syntax Highlighter plugin for that.

      Admin

  16. oiveros says

    hi i’m kind of new on the wordpress theming , and reading about these topic, i wanted to ask you about something related to these . If i want to update the jquery library link how do i do it or where do i find the link i been trying to do it but i can’t find it. Thank you in advanced for your help

    • WPBeginner Support says

      If by updating jquery library link, you mean to add jquery from Google’s library. WordPress comes packed with jquery and to load it in your theme use this line in your theme:

      <?php wp_enqueue_script('jquery'); ?>

      Admin

      • oiveros says

        okey so if i want to have the latest jquery, i just use that line?, because somebody told me to use a plugin just for that, but i wanted to learn how to do it without a plugin

        • oliveros says

          Thank you for your answer, i found the post related to that issue here in your site.

  17. Elliott Richmond says

    Useful Syed, thanks.
    I recently had an issue loading a css file using _underscore as a framework, although the stylesheet was called mycustomstyles.css the theme was calling mycustomstyles.css?ver=xx and the theme wasn’t loading the file because of the naming of the file by appending ?ver=xx to the end of the name.
    Is that something to do with $ver default?

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.