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

Come aggiungere uno shortcode in WordPress (Guida per principianti)

Qui a WPBeginner sentiamo spesso utenti che si sentono sopraffatti dagli shortcode di WordPress. Questi piccoli frammenti di codice possono sembrare confusi all’inizio, ma in realtà sono una delle caratteristiche più potenti di WordPress, se usati correttamente.

Sia che si vogliano aggiungere moduli di contatto, gallerie o layout personalizzati, gli shortcode offrono un modo semplice per inserire caratteristiche complesse senza toccare alcun codice.

In questa guida per principianti, vi mostreremo esattamente come aggiungere shortcode in WordPress, dove posizionarli e i modi migliori per utilizzarli.

Abbiamo giù suddiviso tutto in passaggi semplici e facili da seguire che chiunque può capire, anche se siete completamente inesperti di WordPress.

How to add a shortcode in WordPress

Cosa sono gli shortcode?

Glishortcode in WordPress sono scorciatoie di codice che consentono di aggiungere contenuti dinamici ai post, alle pagine e ai widget della barra laterale di WordPress. Vengono visualizzati all’interno di parentesi quadre come in questo caso:

[myshortcode]

Per capire meglio gli shortcode, diamo un’occhiata ai motivi per cui sono stati aggiunti in primo luogo.

WordPress filtra tutti i contenuti per assicurarsi che nessuno utilizzi i contenuti dei post e delle pagine per inserire codice dannoso nel database. Ciò significa che è possibile scrivere HTML di base nelle pagine pubbliche, ma non è possibile scrivere codice PHP.

Ma se si volesse eseguire del codice personalizzato all’interno dei post per visualizzare post correlati, banner pubblicitari, moduli di contatto, gallerie o altro?

È qui che entra in gioco l’API Shortcode.

In pratica, consente agli sviluppatori di aggiungere il proprio codice all’interno di una funzione e di registrare tale funzione in WordPress come shortcode, in modo che gli utenti possano utilizzarla facilmente senza avere alcuna conoscenza di codifica.

Quando WordPress trova lo shortcode, esegue automaticamente il codice ad esso associato.

Vediamo come aggiungere facilmente gli shortcode alle pagine e ai post di WordPress. Potete utilizzare i link sottostanti per passare al metodo che preferite:

Aggiunta di uno shortcode nei post e nelle pagine di WordPress

Per prima cosa, è necessario modificare il post e la pagina in cui si desidera aggiungere lo shortcode.

Successivamente, è necessario fare clic sul pulsante di aggiunta del blocco ‘+’ per inserire un blocco Shortcode.

Add a shortcode block

Dopo aver aggiunto il blocco Shortcode, è sufficiente inserire lo shortcode nelle impostazioni del blocco.

Lo shortcode sarà fornito da vari plugin di WordPress che potreste utilizzare, come WPForms per i moduli di contatto.

Enter your shortcode

Per approfondire l’uso dei blocchi, vedere il nostro tutorial sull’editor a blocchi di Gutenberg.

Ora è possibile salvare il post o la pagina e visualizzare l’anteprima delle modifiche per vedere lo shortcode in azione.

Aggiunta di uno shortcode nei widget della barra laterale di WordPress

È inoltre possibile utilizzare gli shortcode nei widget della barra laterale di WordPress.

È sufficiente visitare la pagina Aspetto ” Widget e aggiungere un blocco di widget ‘Shortcode’ a una barra laterale.

Add a shortcode widget block

A questo punto, è possibile incollare lo shortcode nell’area di testo del widget.

Non dimenticate di fare clic sul pulsante “Aggiorna” per memorizzare le impostazioni del widget.

Enter shortcode in widget block

Dopodiché, potete visitare il vostro sito web WordPress per vedere l’anteprima live dello shortcode nel widget della barra laterale.

Aggiunta di uno shortcode nel vecchio editor classico di WordPress

Se state ancora utilizzando il vecchio editor classico di WordPress, ecco come potete aggiungere gli shortcode ai vostri post e pagine di WordPress.

È sufficiente modificare la pagina e la pubblicazione in cui si desidera aggiungere lo shortcode. È possibile incollare lo shortcode in qualsiasi punto dell’editor di contenuti in cui si desidera che venga visualizzato. Assicuratevi che lo shortcode sia su una riga a sé stante.

Add shortcode to classic editor

Non dimenticate di salvare le modifiche. Dopodiché, è possibile visualizzare l’anteprima del post e della pagina per vedere lo shortcode in azione.

Aggiunta di uno shortcode nei file del tema di WordPress

Gli shortcode sono destinati a essere utilizzati all’interno di post, pagine e widget di WordPress. Tuttavia, a volte è possibile utilizzare uno shortcode all’interno di un file di tema di WordPress.

WordPress consente di farlo facilmente, ma è necessario modificare i file del tema di WordPress. Se non l’avete mai fatto prima, consultate la nostra guida su come copiare e incollare il codice in WordPress.

In pratica, è possibile aggiungere uno shortcode a qualsiasi modello di tema WordPress semplicemente aggiungendo il seguente codice:

<?php echo do_shortcode('[your_shortcode]'); ?>

A questo punto WordPress cercherà lo shortcode e ne visualizzerà l’output nel modello del tema.

Aggiunta di uno shortcode nei file del tema a blocchi con l’editor del sito completo

Se si utilizza un tema a blocchi, sarà più facile aggiungere shortcode nei file del tema WordPress utilizzando l’editor del sito.

È possibile accedere a questo strumento selezionando Aspetto ” Editor dalla dashboard di WordPress.

Per impostazione predefinita, viene visualizzato il modello di home del tema; è possibile passare ad altri modelli selezionando l’opzione “Modelli”.

Choosing a Template to Edit in the Full Site Editor

Una volta scelto un modello, è possibile iniziare a modificarlo facendo clic nel riquadro destro dell’editor. L’editor riempirà lo schermo.

A questo punto è possibile fare clic sull’icona ‘+’ dell’inseritore di blocchi e cercare il blocco shortcode. Dopodiché, è sufficiente trascinarlo sul modello e digitare lo shortcode che si desidera utilizzare.

Adding a Shortcode Block in the Full Site Editor

Non dimenticate di fare clic sul pulsante “Salva” nella parte superiore della schermata per memorizzare le modifiche.

Creare uno shortcode personalizzato in WordPress

Gli shortcode possono essere molto utili quando si desidera aggiungere contenuti dinamici o codice personalizzato all’interno di pagine e post di WordPress. Tuttavia, se si desidera creare uno shortcode personalizzato, è necessaria una certa esperienza di codifica.

Se si ha dimestichezza con la scrittura di codice PHP, ecco un esempio di codice che si può usare come modello:

// function that runs when shortcode is called
function wpb_demo_shortcode() { 
 
// Things that you want to do.
$message = 'Hello world!'; 
 
// Output needs to be return
return $message;
}
// register shortcode
add_shortcode('greeting', 'wpb_demo_shortcode');

In questo codice, abbiamo prima creato una funzione che esegue del codice e restituisce l’output. Successivamente, abbiamo creato un nuovo shortcode chiamato ‘greeting’ e abbiamo detto a WordPress di eseguire la funzione creata.

È possibile aggiungere questo codice al file functions.php del tema manualmente o utilizzare un plugin per gli snippet di codice come WPCode (consigliato).

Adding Code to WPCode

Consigliamo quest’ultima opzione perché WPCode è il modo più sicuro e semplice per aggiungere codice al vostro sito. Per saperne di più, consultate la nostra recensione di WPCode.

Per maggiori dettagli, potete consultare la nostra guida all’aggiunta di codice personalizzato in WordPress senza rompere nulla.

Una volta fatto ciò, è possibile aggiungere questo shortcode ai post, alle pagine e ai widget utilizzando il seguente codice:

[saluto]

Eseguirà la funzione creata e mostrerà l’output desiderato.

Vediamo ora un utilizzo più pratico di uno shortcode.

In questo esempio, visualizzeremo un banner di Google AdSense all’interno di uno shortcode:

// The shortcode function
function wpb_demo_shortcode_2() { 
 
// Advertisement code pasted inside a variable
$string .= '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-format="fluid"
     data-ad-layout="in-article"
     data-ad-client="ca-pub-0123456789101112"
     data-ad-slot="9876543210"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>';
 
// Ad code returned
return $string; 
 
}
// Register shortcode
add_shortcode('my_ad_code', 'wpb_demo_shortcode_2'); 

Non dimenticate di sostituire il codice dell’annuncio con il vostro codice dell’annuncio.

È ora possibile utilizzare lo shortcode [my_ad_code] all’interno dei post, delle pagine e dei widget della barra laterale di WordPress. WordPress eseguirà automaticamente la funzione associata allo shortcode e visualizzerà il codice pubblicitario.

Shortcodes vs. Blocchi Gutenberg

Gli utenti ci chiedono spesso quali siano le differenze tra shortcode e blocchi Gutenberg.

In sostanza, i blocchi consentono di fare le stesse cose degli shortcode, ma in modo più semplice.

Invece di richiedere agli utenti di aggiungere uno shortcode per visualizzare contenuti dinamici, i blocchi consentono di aggiungere contenuti dinamici all’interno di pagine e post con un’interfaccia utente più intuitiva. Molti popolari plugin di WordPress sono passati a utilizzare i blocchi invece degli shortcode perché sono più facili da usare per i principianti.

Abbiamo messo insieme un elenco dei più utili plugin di blocco Gutenberg per WordPress che potreste voler provare.

Se volete creare i vostri blocchi Gutenberg personalizzati, potete seguire il nostro tutorial passo-passo su come creare blocchi Gutenberg personalizzati in WordPress.

Speriamo che questo articolo vi abbia aiutato a imparare come aggiungere uno shortcode in WordPress. Potreste anche consultare la nostra guida su come mostrare e nascondere il testo nelle pubblicazioni di WordPress con l’effetto “toggle” e il nostro tutorial su come copiare e incollare in WordPress senza problemi di formattazione.

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

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

101 commentiLeave a Reply

  1. Hi All
    in one of my pages I am using this shortcode [product_category category=’jeans’ number=’1000′ per_page=’1000′] . It shows 1000 products of the chosen category jeans. What I can add to this code to make this 1000 products appear same like on product category page or by with a load more button?

  2. English translation –> but something happens when I add the shortcode and then some text, it turns out that this text is inside the html of the shortcode in the frontend, how can I avoid that?

  3. I am creating an own theme, the problem is that theme does no support shortcode. can anyone help me to enable shortcode functionality for my theme.

  4. thanks for sharing such a nice article..
    i want to know how we can use php and html both in short code… waiting for good response thanks…

  5. I installed a Mailchimp for WordPress shortcode ..pasted it at the end of the text version of my document/article & no form was created & this is what it said…..MailChimp for WordPress error: There is no form with ID 0, perhaps it was deleted?

  6. Hi,
    I have a widget by the homepage sidebar from a multisite installation and want to have 1 widget (only one) from this sidebar working at the subsites.
    It is a text widget with a picture, this picture links to an online ebook.

    Do you think I can use this to have it done?

    Many thanks!

  7. The wp form shortcode is not working in pages but it works fine in posts. My website is vinstechs.com. In my website page named Projects is their, in that the shortcode is not working.

    What’s the solution for this, please reply with solution.

  8. I have a slightly more complex question.
    I’m using a theme with a theme options panel.
    I want to use a shortcode inside one of those options.
    However the output is just the [shortcode] text. Is there specific syntax I can use or does it differ from theme to theme? It’s taking forever to get answers from the theme dev.

  9. Hi i am having a problem with [login_widget] shortcode.when i inserted this code to any page/post on wordpress i only get the text but not the login form…i am using login widget with shortcode plugin…please help…

  10. This doesn’t work if you’re trying to place another shortcode within the shortcode you’re creating.

    Say I had a shortcode like [jpshare] and I wanted to place it along with other stuff into another shortcode function like in this article to add to the posts, how would you do that?

    • It clearly stated the code goes into “functions.php”. If you’re not sure how to use the shortcode, it goes anything you add text.

  11. Hello,
    As you can tell from my name I’m very frustrated right now with wordpress.
    >>This last part is simple, just add the [adsense] shortcode in the HTML or Visual views of the Post or Page content editor.<<
    Not even a tiny clue how to do that – would you be willing to expand on this? Thank you

    • WordPress uses shortcodes to add functionality into posts and pages. Like in this tutorial if you wanted to display advertisement code, then you will create a shortcode for it. Once you have created a shortcode you can use it in your posts and pages. Create a new post or edit an existing one and add your shortcode with square brackets in the post content area, like [adsense].

      Admin

      • I installed Popup manager plugin for newsletter subscribers. I got the popup to appear by following your suggestion of putting the shortcode in a comment on my main page. This works but only if a person expands my first comment to read the entire thing. Where/how do I paste the shortcode to get the popup to appear when someone visits my page without requiring them to do anything else? I’m trying to find something in the template customization options but nothing is standing out.

  12. Please help me understand if this is using a shortcode plugin properly. I need to display the date of the last update to a post or page to stop Google structured errors. I am using default 2014 only with plugins. I found a shortcode plugin named “Last Updated Shortcode” that seems to do what I need. I am wondering if this is what I do.

    I would install the plugin, and then activate the plugin. Then on the page/post I would Edit page/post, and at the bottom of the post (or anywhere else if I prefer) add the shortcode. So I would literally type [lastupdated] The last updated date should then appear, correct???

    And hopefully, Google will be happy and stop emailing notices of structured errors.

  13. I’m guessing using the short codes for things like countdown timers is is only for wordpress.org or self hosted wp users correct?

  14. Hi I’m having trouble with the short code [tpe mylang lang=’es, en’] I know WP has recently changed this shortcode replacing the old [tp mylang=”yes” lang=”es, en” ] for the new one, but I’ve done the replacement and I still get to a 404 Nothing found error page, whenever I click on a link with this code. Any Ideas?

  15. I am having trouble figuring out how to add code comments to a page with just shortcode in it. I’ve tried HTML & PHP comment tags and when added the shortcode doesn’t work anymore. The reason I would like to comment the code is that I would like to document information about the shortcode in the page I call it from ( I may not be the site admin forever).

    • WordPress will strip out PHP or HTML comments in post editor. If you were using Edit Flow, then you could leave a note below the post. Right now you can switch to Text editor and leave HTML comment, but as soon as some user views the post in visual editor it will be stripped out again.

      Admin

      • It strips out the comments AND puts in a blank line for each comment. I put the comments below the shortcode and that works fine.
        Thanks for helping me understand what was going on.

  16. When I add shortcode to posts, whether it be in the middle of an article or at the end, the actual element always appears at the top of the post, any idea why?

  17. Simply copy [rx_aeolus_three_cols] and paste it in a WordPress page. Save your page and then preview it. However, you will first have to create your portfolio in the plugin. Otherwise you will not see anything, because there is nothing for the plugin to display.

  18. I have downloaded a plug-in ‘Aeolus portfolio’ for the WordPress 3.9.2 running Twenty Eleven theme. I have been given the following shortcodes in the plug-in setting:

    [rx_aeolus_three_cols]-Displays all portfolio as three columns.

    [rx_aeolus_two_cols]-Displays all portfolio as two columns.

    [rx_aeolus_one_col]-Displays all portfolio as one column.

    Can anyone help as to how these short code can be incorporated in a page. I am new to WP plugins and badly need help.

    Thanks
    Usha

  19. Thanks! This thread helped me a lot.

    Just in case someone else lands in here and need to use a more complex HTML/PHP code structure inside a shortcode, this is an example using some aditional options from the WordPress Shortcodes API documentation:

    Place this (and modify as needed) inside your functions.php:

    http://pastie.org/9454401

    Then you just use this shortcode inside your WordPress content :)

    [mycustomshortcode]

    Greetings!

  20. HI
    I’m beginner and this is my first time with wordpress
    so the first question when i tried this tutorial is in which file i have to write this code ?

  21. Hi,

    Could you please tell me whether i have to put short codes to a particular page if i want any particular plugin to be displayed in that particular page.

    E.g. I’ve installed Collabpress plugin. And i don’t see it’s UI in the front end of my site. So do i have to insert any shortcode to a page for it to be displayed?

  22. I am just a little confused… where am I embedding this shortcode.

    I have a columns plugin that provided the shortcode with a click of a buton, not sure if I have to take the code and embed it in my html.

    please help.

    thanks in advance!

  23. Really? Easy? Simple? This website is great but it says it is for beginners. I’ve been using WordPress for 2 years and yet I did not understand it at all. It’s quite annoying the way geeks always bang on about how easy something is and then write something totally incomprehensible to ordinary humans – just like every Math teacher I ever had.

    OK, write an article that can only be understood by geeks – fine, but please don’t keep telling me how easy it is

    output? string? content editor – where is it? define a function? I wish you would because I don’t know what it is.

    “This function is pretty straightforward – it just returns my Google Adsense code as a string” –
    a string of what? etc etc. Just saying….

    • We totally agree with you that sometimes when writing we may feel that we have explained everything clearly for beginners, but a beginner level user may still not be able to understand it. This is why we have comments and we will be happy to explain it to you more :)

      A shortcode is a short+code. WordPress allows you to generate shortcodes for your programing code blocks called functions. Since a user can not write programming code in the Post Editor when writing a new post. The shortcodes provide users a way to add those programming codes into a post without writing the full code in post editor.

      When WordPress finds a shortcode in a post like this:

      [my_shortcode]

      It then executes the programming code associated with that particular shortcode.

      The example given in the article above, creates a function get_adsense. When this function is executed it outputs the adsense code. We hope this explains it for you. Let us know if you have any more questions.

      Admin

  24. Can I use a shortcode on a Standalone HTML page to link to a page on my blog?

    If so how do I embed it? Does the file need to be a PHP file?

    I can’t seem to find anywhere on the net providing information on using sortcode outside WordPress pages or posts.

  25. Hello, thank you for this, it’s helped a lot.

    However I would like to know how to add more than one adsense in as a shortcode.
    eg [adsense1] – displays one advert [adsense2] displays a different advert.

    Thanks!

  26. Just came across this as I’m looking to add my own shortcodes, I can understand the function part of it, but which document do you include the “hook up”

    “add_shortcode(‘adsense’, ‘get_adsense’); line”

    that would be helpful to me

    Thanks

  27. You forgot to put the semicolon after the ‘ on line 13, which would cause an error, and show people how to call the function. So it would look like this:
     
    </script>
    ‘;
    }
    add_shortcode(‘adsense’, ‘get_adsense’);
     
    But nice job explaining :) Cheers!

  28. I have installed a plugin that uses shortcodes to add styled boxes. I want to add the box to my posts by putting in the single.php. How to insert shortcode content to php file.

    p.s. want to use the box for author info!

  29. I added a shortcode:

    add_shortcode(‘post_title’, ‘get_the_title’);

    which returns post title.. But that post title doen’t displays in rss feed. What may the problem? Where that shortcode [post_title] shoul appear, there is blank space only. Can anyone help me to fix it.. Thank you.

  30. This is pretty basic. The links below will provide a detailed use of wordpress shortcodes.

    http://www.problogdesign.com/wordpress/working-with-wordpress-shortcodes/

    http://www.graphicbeacon.com/how-to-add-a-paypal-donation-shortcode-button-to-your-posts/

    A flexible shortcode is one that will allow you to edit certain attributes. Couldn’t the google adsense code be tweaked to allow the user to set attributes such as the width/height and even ad client?

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.