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

Cómo añadir correctamente JavaScripts y estilos en WordPress

Nota editorial: Ganamos una comisión de los enlaces de socios en WPBeginner. Las comisiones no afectan a las opiniones o evaluaciones de nuestros editores. Más información sobre Proceso editorial.

¿Quieres aprender a añadir correctamente JavaScripts y hojas de estilos CSS en WordPress?

Muchos usuarios de DIY cometen a menudo el error de llamar directamente a sus scripts y hojas de estilos en plugins y temas.

En este artículo, le mostraremos cómo añadir correctamente JavaScript y hojas de estilos en WordPress. Esto será particularmente útil para aquellos que están empezando a aprender el desarrollo de temas y plugins de WordPress.

Properly adding JavaScripts and styles in WordPress

Errores comunes al añadir scripts y hojas de estilos en WordPress

Muchos nuevos desarrolladores de plugins y temas para WordPress cometen el error de añadir directamente sus scripts o CSS integrado en sus plugins y temas.

Algunos utilizan erróneamente la función wp_head para cargar sus scripts y hojas de estilos.

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

Aunque el código anterior puede parecer más fácil, es la forma incorrecta de añadir scripts en WordPress, y da lugar a más conflictos en el futuro.

Por ejemplo, si carga jQuery manualmente y otro plugin carga jQuery a través del método apropiado, entonces tiene jQuery siendo cargado dos veces. Si se carga en cada página, entonces esto afectará negativamente a la velocidad y el rendimiento de WordPress.

También es posible que se trate de versiones diferentes, lo que también puede causar conflictos.

Dicho esto, echemos un vistazo a la forma correcta de añadir scripts y hojas de estilos.

¿Por qué poner en cola scripts y estilos en WordPress?

WordPress cuenta con una sólida comunidad de desarrolladores. Miles de personas de todo el mundo desarrollan temas y plugins para WordPress.

Para asegurarse de que todo funciona correctamente, y nadie está pisando los pies de los demás, WordPress tiene un sistema de cola de espera. Este sistema proporciona una forma programable de cargar JavaScripts y hojas de estilos CSS.

Usando las funciones wp_enqueue_script y wp_enqueue_style, le dice a WordPress cuándo cargar un archivo, dónde cargarlo y cuáles son sus dependencias.

Este sistema también permite a los desarrolladores utilizar las bibliotecas de JavaScript integradas en WordPress en lugar de cargar varias veces el mismo script de terceros. Esto reduce el tiempo de carga de la página y ayuda a evitar conflictos con otros temas y plugins.

¿Cómo poner en cola correctamente los scripts en WordPress?

Cargar scripts correctamente en WordPress es muy fácil. A continuación se muestra un ejemplo de código que se puede pegar en su archivo de plugins, en el archivo functions.php de su tema, o en un plugin de fragmentos de código para cargar correctamente los scripts en 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' );  
?>

Explicación:

Comenzamos registrando nuestro script a través de la función wp_register_script(). Esta función acepta 5 parámetros:

  • $handle – Handle es el nombre único de tu script. El nuestro se llama “my_amazing_script”.
  • $src – src es la ubicación de su script. Estamos usando la función plugins_url para obtener la URL correcta de nuestra carpeta de plugins. Una vez que WordPress encuentre eso, entonces buscará nuestro nombre de archivo amazing_script.js en esa carpeta.
  • $deps – deps es para dependencia. Como nuestro script usa jQuery, hemos añadido jQuery en el área de dependencias. WordPress cargará automáticamente jQuery si no se está cargando ya en el sitio.
  • $ver – Este es el número de versión de nuestro script. Este parámetro no es obligatorio / requerido / necesario.
  • $in_footer – Queremos cargar nuestro script en el pie de página, así que hemos establecido el valor en true. Si quieres cargar el script en la cabecera, entonces lo harías falso.

Después de proporcionar todos los parámetros en wp_register_script, podemos simplemente llamar al script en wp_enqueue_script() que hace que todo suceda.

El último paso es utilizar el gancho de acción wp_enqueue_scripts para cargar el script. Como se trata de un código de ejemplo, lo hemos añadido justo debajo de todo lo demás.

Si estás añadiendo esto a tu tema o plugin, entonces puedes colocar este gancho de acción donde el script es realmente obligatorio / requerido / necesario. Esto le permite reducir la huella de memoria de su plugin.

Ahora algunos se preguntarán ¿por qué vamos a dar el paso extra de registrar el script primero y luego ponerlo en cola? Bueno, esto permite a otros propietarios de sitios dar de baja su script sin modificar el núcleo del código de su plugin.

Poner en cola correctamente los estilos en WordPress

Al igual que los scripts, también puede poner en cola sus hojas de estilos. Mire el ejemplo siguiente:

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

En lugar de utilizar wp_enqueue_script, ahora estamos utilizando wp_enqueue_style para añadir nuestra hoja de estilos.

Aviso que hemos utilizado el gancho de acción wp_enqueue_scripts tanto para estilos como para scripts. A pesar del nombre, esta función funciona para ambos.

En los ejemplos anteriores, hemos utilizado la función plugins_url para apuntar a la ubicación del script o estilo que queríamos poner en cola.

Sin embargo, si está usando la función enqueue scripts en su tema, entonces simplemente use get_template_directory_uri() en su lugar. Si está trabajando con un tema hijo, utilice get_stylesheet_directory_uri().

A continuación se muestra un código de ejemplo:

<?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 artículo te haya ayudado a aprender cómo añadir correctamente JavaScript y estilos en WordPress. También puedes estudiar el código fuente de los mejores plugins de WordPress para ver algunos ejemplos de código de la vida real o comprobar nuestra guía sobre cómo añadir fácilmente JavaScript en entradas o páginas de WordPress.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Descargo: Nuestro contenido está apoyado por los lectores. Esto significa que si hace clic en algunos de nuestros enlaces, podemos ganar una comisión. Vea cómo se financia WPBeginner , por qué es importante, y cómo puede apoyarnos. Aquí está nuestro proceso 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.

El último kit de herramientas de WordPress

Obtenga acceso GRATUITO a nuestro kit de herramientas - una colección de productos y recursos relacionados con WordPress que todo profesional debería tener!

Reader Interactions

36 comentariosDeja una respuesta

  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. Jean-Michel says

    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

  3. Zaved Hossain says

    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.

  4. Hansjörg Leichsenring says

    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

  5. Carlos Araya says

    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 says

      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

  6. Vaibhav Bansal says

    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?

  7. pradyumna says

    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

  8. Vijay.Rajpal says

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

  9. Pramod says

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

  10. Bobbie says

    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.

  11. colkav says

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

  12. xavi says

    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.

  13. Skye Barcus says

    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?

  14. Dejan says

    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!

  15. Adrian Zumbrunnen says

    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 says

      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

  16. oiveros says

    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 says

      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 says

        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 says

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

  17. Elliott Richmond says

    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?

Deja tu comentario

Gracias por elegir dejar un comentario. Tenga en cuenta que todos los comentarios son moderados de acuerdo con nuestros política de comentarios, y su dirección de correo electrónico NO será publicada. Por favor, NO utilice palabras clave en el campo de nombre. Tengamos una conversación personal y significativa.