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

7 consigli essenziali per l’utilizzo degli shortcode 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.

State cercando di utilizzare gli shortcode nel modo giusto sul vostro sito WordPress?

Gli shortcode in WordPress consentono di aggiungere varie funzionalità a post, pagine e widget senza scrivere alcun codice. Molti plugin di WordPress e alcuni temi utilizzano gli shortcode per aggiungere a WordPress diversi elementi, come griglie di prezzi e calendari di eventi.

In questo articolo condivideremo 7 consigli essenziali per l’utilizzo degli shortcode in WordPress.

Using Shortcodes

Cosa sono gli shortcode in WordPress?

Ogni contenuto aggiunto a un sito web WordPress passa attraverso alcuni controlli e filtri di sicurezza. Questi controlli e filtri di sicurezza assicurano che nessun codice dannoso venga inserito in post, pagine, commenti e altro. Ciò significa che non è possibile scrivere direttamente codice in queste aree.

D’altra parte, a volte è sufficiente aggiungere codice in queste aree. Gli shortcode offrono un modo per farlo.

Gli shortcode rendono più facile l’aggiunta di altri elementi ai post di WordPress. Ad esempio, è possibile aggiungere un bellissimo slider reattivo utilizzando un semplice shortcode. È anche possibile creare un modulo di sondaggio complesso in WordPress senza scrivere una sola riga di codice.

Detto questo, diamo un’occhiata ad alcuni suggerimenti per l’utilizzo degli shortcode in WordPress. Potete fare clic sui link sottostanti per passare a qualsiasi suggerimento:

Suggerimento 1: Sapere quando non usare gli shortcode

Gli shortcode sono ottimi, ma utilizzarli in ogni post non è una buona idea. Ci sono molti temi WordPress che dichiarano con orgoglio di avere più di 200 shortcode.

Tuttavia, se si utilizza uno shortcode in ogni post del blog WordPress, si rimane per sempre legati al tema specifico che fornisce lo shortcode.

Se state utilizzando uno shortcode specifico per un tema per creare pulsanti di chiamata all’azione all’interno dei vostri post o pagine, allora dovreste utilizzare la nostra guida sull’aggiunta di pulsanti CSS in WordPress senza utilizzare shortcode.

Se vi ritrovate ad aggiungere lo shortcode in ogni tema per aggiungere lo stesso elemento, come un banner pubblicitario o il testo della firma alla fine del vostro post, allora potreste voler utilizzare un plugin per WordPress o assumere uno sviluppatore per codificarlo direttamente nel vostro tema.

In questo modo, sarà più facile creare lo stile di quell’elemento e rimuoverlo facilmente se si decide di farlo.

Ricordate che se utilizzate uno shortcode in ogni post e in seguito volete rimuoverlo, dovrete modificare tutti i post per rimuoverlo manualmente. Tuttavia, esiste un modo più semplice che vi mostreremo più avanti in questo articolo.

Suggerimento 2: Proteggere gli shortcode dal futuro

Gli shortcode sono ottimi, ma se sono forniti dal tema, è meglio pensarci due volte prima di usarli eccessivamente. Perché?

Perché se si cambia tema, il tema successivo molto probabilmente non avrà lo stesso shortcode.

Il modo migliore per evitarlo è aggiungere un plugin specifico per il sito.

È sufficiente copiare e incollare lo snippet dello shortcode dal file functions.php del tema e poi incollarlo nel plugin specifico del sito.

Tuttavia, non è consigliabile modificare direttamente il file functions.php. Il minimo errore può essere devastante per il sito. Un modo più semplice per aggiungere uno snippet di shortcode al vostro tema è utilizzare il plugin WPCode.

Add a new custom code snippet in WPCode

Rende molto semplice l’aggiunta di snippet di codice al vostro sito e la loro gestione dalla dashboard di WordPress.

Per saperne di più, consultate la nostra guida su come aggiungere codice personalizzato in WordPress.

Suggerimento 3: Come cercare gli shortcode nel vostro tema WordPress

Per proteggere il vostro shortcode in futuro, dovete sapere come si presenta la funzione shortcode e come trovarla nel vostro tema.

Per prima cosa, è necessario aprire la cartella del tema, che di solito si trova in /wp-content/themes/il vostro nome-tema/.

Si deve guardare all’interno del file functions.php o, se il tema ha una cartella includes, all’interno di questa.

Aprire i file e cercare il termine add_shortcode.

Ecco un esempio di come si presenta uno snippet di shortcode:

function my_shortcode_function() { 
$i = '<p>Hello World!</p>';
return $i;
} 
add_shortcode('my-shortcode', 'my_shortcode_function');

Questo codice crea uno shortcode “my-shortcode”, che restituisce un semplice testo di saluto e può essere incorporato in un post o in una pagina di WordPress come questo:

[my-shortcode]

Potete consultare la nostra guida su come creare uno shortcode in WordPress.

Suggerimento 4: Usare gli shortcode nei widget

Gli utenti spesso pensano che gli shortcode siano limitati ai post e alle pagine, ma non è così. È possibile utilizzarli all’interno dei widget di testo di WordPress.

È sufficiente trascinare e rilasciare un widget di testo nella barra laterale e aggiungere lo shortcode al suo interno.

Ricordate che questa funzione non è abilitata di default in WordPress. Se non riuscite a visualizzare il vostro shortcode in un widget, dovete aggiungere questo codice al file functions.php del vostro tema o a un plugin specifico per il sito.

add_filter('widget_text', 'do_shortcode');

Suggerimento 5: Aggiungere uno shortcode nei file del tema

Se, per qualche motivo, si ha la necessità di inserire lo shortcode in un’area non widget del tema, è possibile utilizzare gli shortcode anche lì.

Supponiamo di aver creato un modello di pagina personalizzato e di voler includere uno shortcode per visualizzare un modulo di contatto. Basta aggiungere lo shortcode in questo modo:

<?php echo do_shortcode("[example_shortcode]"); ?>

Se avete bisogno di aiuto, consultate la nostra guida su come incollare gli snippet dal web in WordPress.

Suggerimento 6: Nascondere uno shortcode rotto

Spesso gli utenti cambiano tema senza rendersi conto che i vecchi shortcode non funzionano. A volte lo scoprono dopo mesi, quando un utente visita il suo vecchio post e vi trova un testo strano.

Avete due modi per risolvere il problema. È possibile rimuovere manualmente lo shortcode da ogni post oppure nascondere lo shortcode rotto.

È sufficiente aggiungere il seguente codice al file functions.php del vostro tema o utilizzare WPCode:

add_shortcode( 'shortcodetag', '__return_false' );

Questo codice aggiunge nuovamente lo shortcode orfano senza alcun output. Non dimenticare di sostituire shortcodetag con il nome dello shortcode.

Suggerimento 7: Trovare gli shortcode utilizzati nei post

Se non si vuole utilizzare l’hack del Suggerimento 6 e si desidera rimuovere manualmente tutti gli shortcode, il primo passo è trovare tutti i post che utilizzano lo shortcode.

È possibile utilizzare questo codice nel file functions.php del tema o un plugin specifico per il sito, come WPCode, per fare il lavoro duro al posto vostro:

function wpb_find_shortcode($atts, $content=null) {
ob_start();
extract( shortcode_atts( array(
		'find' => '',
	), $atts ) );

$string = $atts['find'];

$args = array(
	's' => $string,
	);

$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
        echo '<ul>';
	while ( $the_query->have_posts() ) {
	$the_query->the_post(); ?>
	<li><a href="<?php  the_permalink() ?>"><?php the_title(); ?></a></li>
	<?php
	}
        echo '</ul>';
} else {
        echo "Sorry no posts found";
}

wp_reset_postdata();
return ob_get_clean();
}
add_shortcode('shortcodefinder', 'wpb_find_shortcode');

Questo codice crea semplicemente uno shortcode chiamato shortcodefinder. Esegue una query di WordPress ed elenca i post con un determinato tag shortcode.

Ad esempio, se si desidera trovare tutti i post contenenti lo shortcode [contact-form], è sufficiente inserire [shortcodefinder find=’contact-form’] in una pagina di WordPress e salvarla. Ora, se si visualizza l’anteprima della pagina, si potranno vedere tutti i post contenenti lo shortcode.

Per istruzioni più dettagliate, consultate la nostra guida su come trovare e nascondere gli shortcode inutilizzati in WordPress.

Speriamo che questi suggerimenti vi abbiano aiutato a imparare a usare gli shortcode e a sfruttarli al meglio in WordPress. Potreste anche voler consultare la nostra guida definitiva alla SEO di WordPress e come avviare un negozio online.

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

20 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. Justin says

    Hi I’m using Short-codes for layouts in my blog posts (image right, text left, with a lot more responsive styling than Gutenberg can do), but wondering, does this effect the onsite SEO? Are my layouts still rendered as HTML and readable by bots? – Thanks!

    • WPBeginner Support says

      Your content should be rendered as HTML on the front end of the site. The shortcode is for the backend of your site so WordPress knows what content to place there.

      Admin

  3. Alexandre .. says

    the social icons in this article, at the end of the post, are they added by a plugin (what plugin) or hard coded? how can i add them to my own posts?

  4. Seamate says

    I have been trying to use shortcodes, particularly Latex shortcodes in the quiz section of the LMS I am using, all to no avail. The shortcodes are not passed. I have contacted the LMS providers but they are not coming up with any solution, at least, not yet. Is there anything I can do?

  5. Md Abu Selim says

    I wish to learn WordPress Theme Development , So I think that the site is very helpful for me.

  6. Minhaj says

    Hi,
    I want to put my shortcode in html hyper link in button or something.
    like my shortcode is [shortcode]
    and my html code is Dummy

    Then how will I put [shortcode] in html code and my html code is Dummy

  7. marie says

    I have a problem with my short codes in that the text within the buttons does not look very professional as the first letter is only showing half. This is not with every one, just some of them. I would be most grateful for a suggestion

  8. Praveen says

    Hello, I have a question about shortcodes. As I am running a WordPress website that is based on Online Practice Test / Quizzes. To provide these quizzes I am using a plugin and in that plugin I have to add the questions and answers for a quiz. After that I have to put that shortcode in the post.

    My Post Structure
    Title
    [Shortcode]

    then in SEO Title and Description by All in One SEO plugin.

    So my question is, using the only shortcode in all post is safe from the SEO and Google webmasters Guideline point of view ?

    • WPBeginner Support says

      Yes, it is totally safe. The shortcode never appears in the HTML of your website. Like any other PHP funtion, your shortcode is processed by the server and returns the HTML output which is then displayed on your post/page.

      Admin

  9. Giochi MMO says

    There is a way to delete a specific shortcode, maintaining the text inside?

    For example: in this case [dropcap]A[/dropcap] I would like to eliminate the shortcode maintaining the “A”, or any other letter inside.

    Thanks!

  10. Kate Ford says

    I am locked into using a specific theme for business reasons, and it
    lacks some bells and whistles that are necessary and must be used with
    short codes. While the short codes get the job done, there is is one
    element we have to keep in mind:

    Don’t overuse short codes for important text elements if it compromises search engine returns.

    We
    have two plug ins for short codes — one of these keeps the text
    elements right in the post, but the other generates the content in the
    plug in, and only the code is inserted into the post — so there is no
    actual TEXT associated with that post.

    For instance, we created
    some grid like photo galleries using a plug in that relies on short
    codes. The galleries and their captions are created inside the plug-in,
    but only the short code linking to it is published in the post. While
    the post itself has SEO fields to complete, the text (and links) from
    the photo captions actually doesn’t exist IN the post — it exists in
    the output created by the plug-in, which does NOT have SEO fields. When
    I need to edit the gallery, I don’t edit the post, because all it says
    is [Grid 123]. I edit the gallery in the plug-in setting.

    So,
    while it “looks great” on the post, we have to weigh what is most
    important: Does this post need a great looking gallery which may not
    give me any search engine returns, or is the TEXT for gallery more
    important and I need it to be crawled?

    We have a page with FAQ
    and used short codes to make an accordion style display. Toggling a
    question reveals the answer, and then it closes again. On this page, we
    used short codes, but we relied on a different plug in which keeps the
    text IN the post, and simply styles it the way we need. In that manner,
    the text remains part of the post, the word count is accurate, and it
    is crawled by search engines. The short codes merely provide the
    requested style.

    So bottom line, if you have content
    that’s important and should be crawled, avoid short codes if they store
    the information apart or separate from your post.

    • Gyan says

      Hii Tony Franco.

      this is incomplete question. please specify where and which image you want to use. what context you are talking about . ?

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.