Volete aggiungere JavaScript nelle vostre pagine o nei vostri post di WordPress?
A volte è necessario aggiungere codice JavaScript all’intero sito web o a pagine e post specifici. Per impostazione predefinita, WordPress non consente di aggiungere codice direttamente nei post.
In questo articolo vi mostreremo come aggiungere facilmente JavaScript nelle pagine o nei post di WordPress.
Che cos’è JavaScript?
JavaScript è un linguaggio di programmazione che viene eseguito sul browser dell’utente, non sul server. Questa programmazione lato client consente agli sviluppatori di fare molte cose interessanti senza rallentare il sito web.
Se volete incorporare un lettore video, aggiungere calcolatori o qualche altro servizio di terze parti, vi verrà spesso chiesto di copiare e incollare un frammento di codice JavaScript nel vostro sito WordPress.
Un tipico frammento di codice JavaScript può assomigliare a questo:
<script type="text/javascript">
// Some JavaScript code
</script>
<!-- Another Example: --!>
<script type="text/javascript" src="/path/to/some-script.js"></script>
Ma se si aggiunge uno snippet di codice JavaScript a un post o a una pagina di WordPress, questo verrà cancellato da WordPress quando si cercherà di salvarlo.
Detto questo, vediamo come è possibile aggiungere facilmente JavaScript alle pagine o ai post di WordPress, senza rompere il vostro sito web. Potete utilizzare i collegamenti rapidi qui sotto per passare direttamente al metodo che desiderate utilizzare.
Metodo 1. Aggiungere JavaScript ovunque sul vostro sito WordPress usando WPCode (consigliato)
A volte un plugin o uno strumento richiede di copiare e incollare uno snippet di codice JavaScript nel sito web per funzionare correttamente.
Di solito, questi script vengono inseriti nell’intestazione o nel piè di pagina del blog WordPress, in modo che il codice venga caricato a ogni visualizzazione della pagina.
Ad esempio, quando si installa Google Analytics, il codice deve essere eseguito su ogni pagina del sito web, in modo da poter tracciare i visitatori del sito.
È possibile aggiungere manualmente il codice ai file header.php
o footer.php
, ma queste modifiche saranno sovrascritte quando si aggiorna o si cambia il tema.
Per questo motivo consigliamo di utilizzare WPCode per aggiungere JavaScript in qualsiasi punto del sito WordPress.
WPCode è il più potente plugin per snippet di codice disponibile per WordPress. Consente di aggiungere facilmente codice personalizzato a qualsiasi area del sito e, soprattutto, è gratuito.
Per prima cosa, è necessario installare e attivare il plugin gratuito WPCode. Per maggiori dettagli, consultate la nostra guida passo passo su come installare un plugin di WordPress.
Una volta attivato, è necessario andare su Code Snippets ” Headers & Footer.
Qui si vedranno tre campi separati etichettati “Intestazione”, “Corpo” e “Piè di pagina”.
Ora è possibile aggiungere il codice JavaScript in una di queste caselle e poi fare semplicemente clic sul pulsante ‘Salva’. WPCode caricherà automaticamente il codice aggiunto in ogni pagina del vostro sito web.
È inoltre possibile aggiungere snippet di codice in qualsiasi altro punto del sito, ad esempio all’interno di post o pagine.
Per farlo, basta andare su Code Snippets ” + Add Snippet e poi cliccare su ‘Create Your Own’.
Verrà visualizzata la pagina “Crea snippet personalizzato”, dove è possibile aggiungere un titolo al codice e incollarlo nella casella “Anteprima codice”.
Quindi, selezionare “Snippet JavaScript” dal menu a discesa “Tipo di codice”.
Quindi, scorrere fino a trovare la sezione “Inserimento”.
Ora non resta che selezionare una ‘posizione’ per il codice dal menu a discesa. Trovate “Pagina, Post, Tipo di post personalizzato” e scegliete in quale punto della pagina o del post volete che il codice appaia.
Se si sceglie di far inserire a WPCode lo snippet prima o dopo un paragrafo, si potrà scegliere quale paragrafo specifico del post dovrà apparire prima o dopo.
Ad esempio, se si inserisce 1 nel campo “Inserisci numero”, il frammento di codice apparirà prima o dopo il primo paragrafo. Utilizzare 2 per il secondo paragrafo e così via.
A questo punto, è sufficiente fare clic sulla levetta vicino alla parte superiore dello schermo per passare ad “Attivo” e quindi fare clic sul pulsante “Salva frammento” accanto ad esso.
Questo è tutto ciò che serve per far vivere il vostro snippet di codice sul sito!
Metodo 2. Aggiungere manualmente il codice JavaScript a WordPress usando il codice (avanzato)
Con questo metodo, è necessario aggiungere del codice ai file di WordPress. Se non l’avete mai fatto prima, consultate la nostra guida su come copiare e incollare codice in WordPress.
Per prima cosa, vi mostreremo come aggiungere il codice all’intestazione del vostro sito WordPress. È necessario copiare il codice seguente e aggiungerlo al file functions.php.
function wpb_hook_javascript() {
?>
<script>
// your javscript code goes
</script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
Aggiungere JavaScript a un post specifico di WordPress usando il codice
Se si desidera aggiungere JavaScript solo a un singolo post di WordPress, è necessario aggiungere una logica condizionale al codice.
Date un’occhiata al seguente frammento di codice:
function wpb_hook_javascript() {
if (is_single ('5')) {
?>
<script type="text/javascript">
// your javscript code goes here
</script>
<?php
}
}
add_action('wp_head', 'wpb_hook_javascript');
Il codice qui sopra eseguirà il JavaScript solo se l’ID del post corrisponde a ‘5’. Assicurarsi di sostituire ‘5’ con l’ID del proprio post.
Per trovare l’ID del post, aprire il post in cui si desidera eseguire il JavaScript. Poi, nell’URL della pagina, si troverà l’ID del post.
Aggiunta di JavaScript a una pagina specifica di WordPress tramite codice
Se volete aggiungere JavaScript solo a una singola pagina di WordPress, dovrete aggiungere la logica condizionale al codice, proprio come sopra.
Osservate il seguente esempio:
function wpb_hook_javascript() {
if (is_page ('10')) {
?>
<script type="text/javascript">
// your javscript code goes here
</script>
<?php
}
}
add_action('wp_head', 'wpb_hook_javascript');
Il codice qui sopra eseguirà il JavaScript solo se l’ID della pagina è ’10’. Assicurarsi di sostituire ’10’ con l’ID della propria pagina.
È possibile trovare l’ID della pagina con lo stesso metodo descritto sopra. È sufficiente aprire la pagina su cui si desidera eseguire il JavaScript e annotare l’ID della pagina nell’URL.
Aggiungere JavaScript a un post o a una pagina specifica di WordPress utilizzando il codice nel piè di pagina
Se si desidera che il JavaScript venga eseguito nel piè di pagina del sito anziché nell’intestazione, è possibile aggiungere il seguente frammento di codice al sito web.
function wpb_hook_javascript_footer() {
?>
<script>
// your javscript code goes
</script>
<?php
}
add_action('wp_footer', 'wpb_hook_javascript_footer');
Questo frammento di codice si aggancia a wp_footer
invece che a wp_head
. È anche possibile aggiungere tag condizionali per aggiungere JavaScript a specifici post e pagine, come negli esempi precedenti.
Nota: questi metodi sono per i principianti e per i proprietari di siti web. Se state imparando lo sviluppo di temi o plugin di WordPress, dovete inserire correttamente JavaScript e fogli di stile nei vostri progetti.
Speriamo che questo articolo vi abbia aiutato a capire come aggiungere facilmente JavaScript alle pagine o ai post di WordPress. Potreste anche voler consultare la nostra guida su come scegliere la migliore piattaforma di blogging e la nostra selezione di esperti del miglior software di chatbot AI per il vostro sito web.
Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.
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!
wing says
i wonder why not use the most simple method, just directly use the wordpress “Custom HTML” block to insert Javascript code to a post or page. I have try it and test it. No problem. very very very simple method.
WPBeginner Support says
It would depend on the specific code, the methods we show in this guide are to add the code to the head section as most JavaScript wants to be run in the head section.
Admin
Rejane says
I have an active child theme and I used the “Insert Headers and Footer” plugin to add a JavaScript code for an email marketing service. It worked out! But unfortunately, I had to cancelled my account with this service and now I would like to remove the JavaScript code. How do I do this when I am using a child theme? Is there any easy way or another plugin for this?
WPBeginner Support says
You would remove the code from the Insert Headers and Footers plugin and it would remove the code from your site
Admin
Paul Liles says
I cannot find the three-dot menu anywhere? Need some help.
WPBeginner Support says
It should be at the top of the edit page. if you are using the classic editor then it would be under Screen Options.
Admin
Eleni says
I’m not getting the Custom Fields option in the Screen Options tab. I’m using a self-hosted website and have installed and activated the Code Embed plugin
WPBeginner Support says
If you’re using the Block editor then the setting has moved under the preferences area.
Admin
Ashley says
This site is AMAZING!!! This is the third post in a row where I’ve hit the jackpot getting what I needed and did it in the easiest way possible. Thank you!!
WPBeginner Support says
Glad our guides were helpful
Admin
Dude says
Hey, great stuff WPbeginners! The second method worked like a charm. I did have a question though. If I wanted to add another js code for another purpose, how should the code start. Because anything I add after the code is greyed out. I’m at a loss here. I want it to do the same but for another page. Any ideas will be appreciated.
WPBeginner Support says
It would heavily depend on the code you are using but you would want to ensure the code is before the
/script
tagAdmin
Jonathan says
Thanks. This article was exceedingly helpful. I went with the functions.php option. Worked well.
WPBeginner Support says
Glad our guide was helpful
Admin
Elise says
That worked. Thank you so much!
WPBeginner Support says
You’re welcome
Admin
Martin says
Question on Method 3:
After inputting the value and clicking on the “add custom field”, how do I get the code to display on my website frontend?
Should I insert “{{CODEmyjscode}}” using a shortcode widget or text editor on the page?
WPBeginner Support says
for the moment you would want to use the text or code editor.
Admin
Bret Bernhoft says
When I first began working with WordPress, JavaScript seemed like an impossibility for me. But fast forward to today and I’m writing the language every day; often in association with WordPress.
I wish it had been clearer to me how easy it would have been to write JavaScript, when I first began this journey. Thank you for the tools and tips. I’ll have to give this a try.
WPBeginner Support says
Glad we could share some easy methods for adding JavaScript to your site!
Admin
ibrahim says
It worked and helped me a lot. Thank you!
WPBeginner Support says
You’re welcome
Admin
Kat says
I tried adding custom JS in my post, but nothing happens. I followed your exact directions for Method 3, but when I go to preview the page it’s just blank space where the JS is supposed to be. Any idea why?
WPBeginner Support says
You would want to take a look at the plugin’s FAQ for the most common reasons for that issue and how to resolve it.
Admin
Samuel says
How does this work with the new WordPress block system?
I’m trying to embed this in a page, but it just shows as {{code1}} on the preview
WPBeginner Support says
It would depend on the method you are using on your site for the plugin, they have an update in their FAQ section for how to use it at the moment.
Admin
Akash says
Thank for this information. Really amazing and helpful post.
WPBeginner Support says
You’re welcome, glad our article was helpful
Admin
Alex says
Hey, great guide! The problem is I don’t have “Custom Fields” under screen options… Any idea why?
WPBeginner Support says
Is your site on WordPress.com?
Admin
James says
Hi. I have employed a programmer to create a tool, which he did in Javascript. I have been using Weebly but Weebly has become unresponsive to requests for help, to which hundreds of blogs testify. So, I’m looking at alternatives to Weebly. Could WordPress handle a 2 MB javascript tool?
Thanks,
WPBeginner Support says
Your hosting would determine if a tool like that could be used not the platform for your website and depending on how the tool was set up would determine if you can transfer the tool.
Admin
Matt says
What if I need to add the script just on a single page but in the head not the body? I am trying to add a google conversion pixel just to my form submit thank you page.
WPBeginner Support says
You would want to take a look at the section of the article called: Adding JavaScript to a Specific WordPress Post or Page Using Code
Admin
quy says
it works like magic. Thanks very much
WPBeginner Support says
You’re welcome, glad our article could help
Admin
Manjeet Chhillar says
Thank you for this very helpful post.
My query is: How can I implement “Method 2” on multiple posts. Do i need to add Post ID of every single post separated by comma?
WPBeginner Support says
yes, you would need to place the commas outside the single quotes and start a new set of quotes for this method
Admin
Deborah says
Thank you for sharing the three methods WordPress users can use to add JavaScript to posts or pages. From what I read on the Insert Headers and Footers plugin page in the repository, the plugin doesn’t use the enqueue method to add the scripts. Which is the recommended method to add scripts in WordPress.
Did I misunderstand? Or is Insert Headers and Footers using enqueue to add scripts? If it’s not using enqueue, do you know when the plugin will be updated to use enqueue?
WPBeginner Support says
The plugin is not enqueueing scripts added to it at the moment as not everything added with our plugin may not want to be enqueued. If you would like to enqueue the added code you would want to use another method.
Admin
Dave G says
Nice, thanks for that. It so happen that the exact post ID I needed to run javascript on was number 16. “`if (is_single (’16’)) { “`
Are you from the future?
WPBeginner Support says
Not yet at least
Admin
Golu Arjun says
Thank you for this post. It’s very helpful. It is possible to customize
WPBeginner Support says
You’re welcome
Admin
Thomas says
I need to add a script to all posts in my blog. I have the plugin to each individual post. Thing is, there are thousands of posts and we need to add the script to all of them. Any suggestions? Thank you in advance.
WPBeginner Support says
The Insert Headers and footers option will put a code on every post and page for you if they are using the same code.
Admin
Thomas says
Thank you for your quick reply.
We only want the script to run on Posts. We do not want it to run on all pages.
WPBeginner Support says
If you had a widget that is only added to posts you could try adding the code in a widget.
Ann says
I’ve tried using the Headers and Footers scripts and the jQuery just doesn’t seem to be working properly.
WPBeginner Support says
It would depend on the specific code you are adding to the site for the possible reasons it could not be working. You may want to ensure with who you took the code from that the code itself is working.
Admin
Andrew Golay says
Please fix your Headers / Footer plugin or change this article, thank you.
WPBeginner Support says
Our plugin is currently working from testing but we will certainly take another look at it.
Admin
lynn says
thank you!! This was very helpful .
WPBeginner Support says
Glad it was helpful
Admin
Remco says
Thank you for this great post!
Is it possible to implement Structured Data on Woocommerce pages with this method (JSON-LD)?
WPBeginner Support says
You likely could but if you have an SEO plugin you are currently using you would want to check with that plugin to see if the plugin does that already.
Admin
graham says
A well-presented roundup of the better-known options for what is becoming a common need. However, many WordPress users are not (and do not want to be) programmers. For them, JavaScript in any form is too frightening; that’s why they use WordPress with its promise of “no programming required”.
There’s another possibility; to use custom scripts instead of JavaScript, and embed them directly in the page. You can put them in any component, though I prefer .
All you need then is something that can compile and run the script. It’s hard to find plugins that can do this; my own searches haven’t yet turned up any. However, as a JavaScript programmer myself, I was able to write one and put it in the library as EasyCoder. The scripts resemble English, have about the same complexity as SQL and can do most of the things commonly required to manage content and interactivity in a web page. EasyCoder is also fully pluggable so other programmers can add modules themselves.