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

Como adicionar um código curto no WordPress (guia para iniciantes)

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Você deseja adicionar códigos de acesso no WordPress, mas não sabe como começar?

Os códigos de acesso são uma maneira fácil de adicionar conteúdo dinâmico a seus posts, páginas e barras laterais do WordPress. Muitos plugins e temas do WordPress usam códigos de acesso para adicionar conteúdo especializado, como formulários de contato, galerias de imagens, controles deslizantes e muito mais.

Neste artigo, mostraremos a você como adicionar facilmente um shortcode no WordPress. Também mostraremos como criar seus próprios códigos de acesso personalizados no WordPress.

How to add a shortcode in WordPress

O que são códigos curtos?

Os códigos de acesso no WordPress são atalhos de código que ajudam você a adicionar conteúdo dinâmico a posts, páginas e widgets da barra lateral do WordPress. Eles são exibidos dentro de colchetes como este:

[myshortcode]

Para entender melhor os códigos de acesso, vamos dar uma olhada no histórico do motivo pelo qual eles foram adicionados em primeiro lugar.

O WordPress filtra todo o conteúdo para garantir que ninguém use o conteúdo de posts e páginas para inserir códigos maliciosos no banco de dados. Isso significa que você pode escrever HTML básico em suas postagens, mas não pode escrever código PHP.

Mas e se você quisesse executar algum código personalizado dentro das suas postagens para exibir postagens relacionadas, anúncios em banner, formulários de contato, galerias ou qualquer outra coisa?

É aqui que entra a API Shortcode.

Basicamente, ele permite que os desenvolvedores adicionem seu código dentro de uma função e, em seguida, registrem essa função no WordPress como um shortcode, para que os usuários possam usá-lo facilmente sem ter nenhum conhecimento de codificação.

Quando o WordPress encontrar o shortcode, ele executará automaticamente o código associado a ele.

Vamos ver como adicionar facilmente códigos de acesso às suas postagens e páginas do WordPress. Você pode usar os links abaixo para ir para o método de sua preferência.

Adição de um código curto em posts e páginas do WordPress

Primeiro, você precisa editar o post e a página em que deseja adicionar o shortcode.

Depois disso, você precisa clicar no botão de adicionar bloco “+” para inserir um bloco de Shortcode.

Add a shortcode block

Depois de adicionar o bloco Shortcode, basta inserir seu shortcode nas configurações do bloco.

O shortcode será fornecido por vários plug-ins do WordPress que você pode estar usando, como o WPForms para formulários de contato ou o OptinMonster para marketing por e-mail.

Enter your shortcode

Para saber mais sobre como usar blocos, consulte nosso tutorial do Gutenberg para obter mais detalhes.

Agora você pode salvar seu post ou página e visualizar suas alterações para ver o shortcode em ação.

Adição de um código curto nos widgets da barra lateral do WordPress

Você também pode usar códigos de acesso nos widgets da barra lateral do WordPress.

Basta acessar a página Appearance ” Widgets e adicionar um bloco de widget “Shortcode” a uma barra lateral.

Add a shortcode widget block

Agora, você pode colar seu shortcode na área de texto do widget.

Não se esqueça de clicar no botão “Update” (Atualizar) para armazenar as configurações do widget.

Enter shortcode in widget block

Depois disso, você pode visitar seu site do WordPress para ver a visualização ao vivo do shortcode no widget da barra lateral.

Adição de um código curto no antigo editor clássico do WordPress

Se você ainda estiver usando o antigo editor clássico do WordPress, veja como adicionar códigos de acesso às suas postagens e páginas do WordPress.

Basta editar o post e a página em que você deseja adicionar o shortcode. Você pode colar o shortcode em qualquer lugar dentro do editor de conteúdo onde deseja que ele seja exibido. Apenas certifique-se de que o shortcode esteja em sua própria linha.

Add shortcode to classic editor

Não se esqueça de salvar suas alterações. Depois disso, você pode visualizar sua postagem e página para ver o shortcode em ação.

Adição de um código curto nos arquivos de tema do WordPress

Os códigos de acesso devem ser usados em posts, páginas e widgets do WordPress. No entanto, às vezes, você pode querer usar um shortcode em um arquivo de tema do WordPress.

O WordPress facilita essa tarefa, mas você precisará editar os arquivos de tema do WordPress. Se você nunca fez isso antes, consulte nosso guia sobre como copiar e colar código no WordPress.

Basicamente, você pode adicionar um shortcode a qualquer modelo de tema do WordPress simplesmente adicionando o seguinte código:

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

O WordPress agora procurará o shortcode e exibirá sua saída no modelo do tema.

Adição de um código curto em arquivos de tema de bloco com o Full-Site Editor

Se estiver usando um tema de bloco, será mais fácil adicionar códigos de acesso nos arquivos de tema do WordPress usando o editor de site completo.

Você pode acessar essa ferramenta selecionando Appearance ” Editor no painel do WordPress.

Por padrão, você verá o modelo inicial do seu tema e poderá alternar para outros modelos selecionando a opção “Templates”.

Choosing a Template to Edit in the Full Site Editor

Depois de escolher um modelo, você pode começar a editá-lo clicando no painel direito do editor. O editor agora preencherá a tela.

Agora você pode clicar no ícone de inserção de bloco “+” e procurar o bloco de shortcode. Depois disso, basta arrastá-lo para o modelo e digitar o shortcode que deseja usar.

Adding a Shortcode Block in the Full Site Editor

Não se esqueça de clicar no botão “Save” (Salvar) na parte superior da tela para armazenar suas alterações.

Criando seu próprio código de acesso personalizado no WordPress

Os códigos de acesso podem ser muito úteis quando você deseja adicionar conteúdo dinâmico ou código personalizado dentro das postagens e páginas do WordPress. No entanto, se você quiser criar um shortcode personalizado, será necessário ter alguma experiência em codificação.

Se você se sente à vontade para escrever código PHP, aqui está um exemplo de código que pode ser usado como modelo:

// 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');

Nesse código, primeiro criamos uma função que executa um código e retorna o resultado. Depois disso, criamos um novo shortcode chamado ‘greeting’ e dissemos ao WordPress para executar a função que criamos.

Você pode adicionar esse código ao arquivo functions.php do seu tema manualmente ou usar um plug-in de snippet de código como o WPCode.

Adding Code to WPCode

Para obter mais detalhes, consulte nosso guia para adicionar código personalizado no WordPress sem quebrar nada.

Depois de fazer isso, você pode adicionar esse shortcode a seus posts, páginas e widgets usando o seguinte código:

[saudação]

Ele executará a função que você criou e mostrará o resultado desejado.

Agora, vamos dar uma olhada em um uso mais prático de um shortcode.

Neste exemplo, exibiremos um banner do Google AdSense em um 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'); 

Não se esqueça de substituir o código do anúncio por seu próprio código de anúncio.

Agora você pode usar o shortcode [my_ad_code] em seus posts, páginas e widgets da barra lateral do WordPress. O WordPress executará automaticamente a função associada ao shortcode e exibirá o código do anúncio.

Shortcodes vs. Blocos do Gutenberg

Os usuários nos perguntam com frequência sobre as diferenças entre os códigos de acesso e os blocos do Gutenberg.

Basicamente, os blocos permitem que você faça o mesmo que os códigos de acesso, mas de uma forma mais fácil de usar.

Em vez de exigir que os usuários adicionem um shortcode para exibir conteúdo dinâmico, os blocos permitem que os usuários adicionem conteúdo dinâmico dentro de posts/páginas com uma interface de usuário mais intuitiva. Muitos plug-ins populares do WordPress passaram a usar blocos em vez de códigos de acesso porque são mais fáceis de usar para iniciantes.

Reunimos uma lista dos plug-ins de bloco Gutenberg mais úteis para o WordPress que você pode querer experimentar.

Se quiser criar seus próprios blocos personalizados do Gutenberg, você pode seguir nosso tutorial passo a passo sobre como criar blocos personalizados do Gutenberg no WordPress.

Esperamos que este artigo tenha ajudado você a aprender como adicionar um shortcode no WordPress. Talvez você também queira ver nosso guia sobre como criar um tema personalizado do WordPress sem escrever nenhum código e nossa seleção de especialistas dos melhores plug-ins de arrastar e soltar do construtor de páginas do WordPress.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

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.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

102 ComentáriosDeixe uma resposta

  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. Andrew Wilson says

    Hi Guys,

    Is it possible with this plugin to create a unique QR Code for users that sign up to your website?

    i.e. a person registers on the website, and as part of that process the back-end creates a unique QR Code for that user which if scanned by a third party takes them to their profile on the website?

  3. Moinuddin Waheed says

    This is very helpful for making our own custom short codes.
    I have been using short codes for a while and have thought of making my own short codes to use but was not aware about the process.
    I have a bit of coding knowledge and can easily make shortcodes through php functions.
    Thanks for the guide.

  4. Jiří Vaněk says

    Thank you for the detailed instructions. I was able to add the shortcode to Gutenberg but could not use it as a php code. At the same time, it is evidently that simple. A bit smarter again thanks to wpbeginner.

    • WPBeginner Support says

      Thank you for pointing that out, it works as a good reminder to make sure you spell your shortcodes correctly :)

      Administrador

  5. Hugh says

    Thanks for the great article. Works like a charm. However, although it is explained on the page link provided in the article, it may have been helpful to many readers if you had reiterated that to create shortcodes yourself (‘How to Create Your Own Custom Shortcode’ section of the article), you simply add the example code provided or your own code to the theme’s (or child theme’s) ‘functions.php’ file. Thanks again! :)

    • WPBeginner Support says

      You would need to use the method for the theme files from this article and add it to your theme’s header file.

      Administrador

  6. Tihomir says

    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?

  7. Jose Rodriguez says

    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?

  8. loganathan says

    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.

  9. Ihsan says

    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…

  10. Melissa Lowe says

    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?

  11. Helena says

    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!

  12. Vinayak Ganiger says

    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.

  13. Meryl says

    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.

  14. hirak das says

    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…

  15. Armen says

    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?

    • Drew says

      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.

  16. Ihatewordpress says

    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

    • WPBeginner Support says

      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].

      Administrador

      • Brock says

        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.

  17. Patty says

    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.

  18. Larry Leek says

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

  19. Anibal says

    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?

  20. Steve says

    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).

    • WPBeginner Support says

      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.

      Administrador

      • Steve says

        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.

  21. Michael says

    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?

  22. WPBeginner Staff says

    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.

  23. Usha says

    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

  24. Dan says

    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!

  25. Aymen Benzarti says

    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 ?

  26. Nidesh says

    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?

  27. Amber T says

    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!

  28. Carol Manser says

    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….

    • WPBeginner Support says

      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.

      Administrador

  29. Alan Murray says

    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.

  30. Luke Ward says

    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!

  31. Paul says

    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

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.