Directory

Como adicionar corretamente JavaScripts e estilos no WordPress
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 corretamente JavaScripts e estilos no WordPress

Você quer aprender a adicionar corretamente JavaScripts e folhas de estilo CSS no WordPress?

Muitos usuários do tipo “faça você mesmo” cometem o erro de chamar diretamente seus scripts e folhas de estilo em plug-ins e temas. Com base em nossa experiência, isso pode causar vários problemas posteriormente.

Neste artigo, mostraremos a você como adicionar corretamente JavaScript e folhas de estilo no WordPress. Isso será particularmente útil para aqueles que estão começando a aprender o desenvolvimento de temas e plugins do WordPress.

Properly adding JavaScripts and styles in WordPress

Erro comum ao adicionar scripts e folhas de estilo no WordPress

Muitos novos desenvolvedores de plug-ins e temas do WordPress cometem o erro de adicionar diretamente seus scripts ou CSS em linha a seus plug-ins e temas.

Algumas pessoas usam erroneamente a função wp_head para carregar seus scripts e folhas de estilo.

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

Embora o código acima possa parecer mais fácil, essa é a maneira incorreta de adicionar scripts no WordPress e gera mais conflitos no futuro.

Por exemplo, se você carregar o jQuery manualmente e outro plug-in carregar o jQuery pelo método adequado, o jQuery será carregado duas vezes. Se ele for carregado em todas as páginas, isso afetará negativamente a velocidade e o desempenho do WordPress.

Também é possível que os dois sejam versões diferentes, o que também pode causar conflitos.

Dito isso, vamos dar uma olhada na maneira correta de adicionar scripts e folhas de estilo.

Por que enfileirar scripts e estilos no WordPress?

O WordPress tem uma forte comunidade de desenvolvedores. Milhares de pessoas de todo o mundo desenvolvem temas e plug-ins para o WordPress.

Para garantir que tudo funcione corretamente e que ninguém esteja pisando nos pés dos outros, o WordPress tem um sistema de enfileiramento. Esse sistema fornece uma maneira programável de carregar JavaScripts e folhas de estilo CSS.

Ao usar as funções wp_enqueue_script e wp_enqueue_style, você informa ao WordPress quando carregar um arquivo, onde carregá-lo e quais são suas dependências.

Esse sistema também permite que os desenvolvedores utilizem as bibliotecas JavaScript integradas que vêm junto com o WordPress, em vez de carregar o mesmo script de terceiros várias vezes. Isso reduz o tempo de carregamento da página e ajuda a evitar conflitos com outros plug-ins e temas.

Como enfileirar corretamente os scripts no WordPress?

Carregar scripts corretamente no WordPress é muito fácil. Abaixo está um exemplo de código que você colaria no arquivo de plug-ins, no arquivo functions.php do tema ou em um plug-in de snippets de código para carregar corretamente os scripts no 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' );  
?>

Explicação:

Começamos registrando nosso script por meio da função wp_register_script(). Essa função aceita 5 parâmetros:

  • $handle – Handle é o nome exclusivo do seu script. O nosso se chama “my_amazing_script”
  • $src – src é o local do seu script. Estamos usando a função plugins_url para obter o URL correto da nossa pasta de plugins. Quando o WordPress encontrar essa pasta, ele procurará o nome do arquivo amazing_script.js nessa pasta.
  • $deps – deps significa dependência. Como nosso script usa jQuery, adicionamos jQuery na área de dependência. O WordPress carregará automaticamente o jQuery se ele ainda não estiver sendo carregado no site.
  • $ver – Esse é o número da versão do nosso script. Esse parâmetro não é obrigatório.
  • $in_footer – Queremos carregar nosso script no rodapé, por isso definimos o valor como true. Se você quiser carregar o script no cabeçalho, então você deve definir esse valor como falso.

Depois de fornecer todos os parâmetros em wp_register_script, podemos simplesmente chamar o script em wp_enqueue_script(), o que faz com que tudo aconteça.

A última etapa é usar o gancho de ação wp_enqueue_scripts para realmente carregar o script. Como este é um código de exemplo, adicionamos esse gancho logo abaixo de todo o resto.

Se você estiver adicionando isso ao seu tema ou plug-in, poderá colocar esse gancho de ação onde o script for realmente necessário. Isso permite reduzir o consumo de memória do seu plug-in.

Algumas pessoas podem se perguntar por que estamos dando um passo a mais para registrar o script primeiro e depois enfileirá-lo? Bem, isso permite que outros proprietários de sites cancelem o registro do seu script sem modificar o código principal do seu plug-in.

Enfileirar estilos adequadamente no WordPress

Assim como os scripts, você também pode enfileirar suas folhas de estilo. Veja o exemplo abaixo:

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

Em vez de usar wp_enqueue_script, agora estamos usando wp_enqueue_style para adicionar nossa folha de estilo.

Observe que usamos o gancho de ação wp_enqueue_scripts tanto para estilos quanto para scripts. Apesar do nome, essa função funciona para ambos.

Nos exemplos acima, usamos a função plugins_url para apontar para o local do script ou estilo que queríamos enfileirar.

No entanto, se estiver usando a função enqueue scripts no seu tema, basta usar get_template_directory_uri(). Se estiver trabalhando com um tema filho, use get_stylesheet_directory_uri().

Abaixo está um exemplo de código:

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

Esperamos que este artigo tenha ajudado você a aprender como adicionar corretamente JavaScript e estilos no WordPress. Talvez você também queira estudar o código-fonte dos principais plug-ins do WordPress para obter alguns exemplos reais de código ou conferir nosso guia sobre como adicionar JavaScript facilmente em posts ou 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

36 ComentáriosDeixe uma resposta

  1. Syed Balkhi

    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. Schroedingers Katze

    Cheers, thanks for sharing! Great explanation.

    • WPBeginner Support

      You’re welcome :)

      Administrador

  3. Jean-Michel

    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

  4. Orhan

    This article was very useful to me. Thank you.

  5. Mark

    Typical article that makes you even more confused after than before…

  6. Zaved Hossain

    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.

  7. Hansjörg Leichsenring

    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

  8. Carlos Araya

    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

      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

  9. Vaibhav Bansal

    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?

  10. pradyumna

    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

  11. Vijay.Rajpal

    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!!!!!

    • WPBeginner Support

      There is an unexpected { in the code. Go to the line 18 of your functions file and then carefully study the code. You may have forgotten some tiny code like a missing ;

      Administrador

  12. Pramod

    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’);

  13. Bobbie

    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.

  14. colkav

    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 :(

  15. Shoaib

    Is there any Plugin for the same … i am newbie and can’t play with codes … Plz Help me Sir

  16. xavi

    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.

  17. Skye Barcus

    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?

  18. Tyler Longren

    On the style loading piece, on line 6, wp_register_script, should be wp_register_style I believe.

      • Pedro de Carvalho

        why you chose to use _script instead?

        • Pali Madra

          I would also like to know why use _script and not _style? Are there any benefits or will both work therefore either can be used?

  19. Dejan

    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!

  20. Adrian Zumbrunnen

    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

      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.

      Administrador

  21. oiveros

    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

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

      Administrador

      • oiveros

        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

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

  22. Mark

    Thanks so much for this tut.

  23. Elliott Richmond

    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?

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.