Family Encyclopedia >> Electronics

How to correctly add JavaScripts and styles in WordPress

Do you want to learn how to properly add JavaScripts and CSS style sheets in WordPress? Many DIY users often make the mistake of directly calling their scripts and style sheets in plugins and themes. In this article, we will show you how to properly add JavaScripts and style sheets in WordPress. This will be particularly useful for those who are just starting to learn WordPress theme and plugin development.

How to correctly add JavaScripts and styles in WordPress

Common error when adding scripts and style sheets in WordPress

Many new WordPress plugin and theme developers make the mistake of directly adding their inline scripts or CSS to their plugins and themes.

Some mistakenly use wp_head Function to load your scripts and style sheets.

 

While the code above may seem easier, it is the wrong way to add scripts in WordPress and leads to more conflicts in the future.

For example, if you load jQuery manually and another plugin loads jQuery through the proper method, then jQuery is loaded twice. If it loads on all pages, this will negatively affect the speed and performance of WordPress.

It is also possible that the two are different versions which can also cause conflicts.

With that said, let's take a look at the correct way to add scripts and style sheets.

Why enqueue scripts and styles in WordPress?

WordPress has a strong community of developers. Thousands of people from all over the world develop themes and plugins for WordPress.

To make sure everything works properly, and no one steps on anyone else's toes, WordPress has a queuing system. This system provides a programmable way to load JavaScripts and CSS style sheets.

By using the wp_enqueue_script and wp_enqueue_style functions, you tell WordPress when to upload a file, where to upload it, and what its dependencies are.

This system also allows developers to use the built-in JavaScript libraries that come bundled with WordPress instead of loading the same third-party script multiple times. This reduces page load time and helps avoid conflicts with other themes and plugins.

How to properly enqueue scripts in WordPress?

Loading scripts correctly in WordPress is very easy. Below is an example code that you would paste into your plugins file or your theme's functions.php file to properly load the scripts into 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'); ?> 

Explanation:

We start by registering our script via wp_register_script () function. This function accepts 5 parameters:

  • $ handle - Handle is the unique name of your script. Ours is called "my_amazing_script"
  • $ src - src is the location of your script. We are using the plugins_url function to get the correct URL of our plugins folder. Once WordPress finds that, it will look for our amazing_script.js filename in that folder.
  • $ deps - Deps is for dependency. Como nuestro script usa jQuery, hemos agregado jQuery en el área de dependencia. WordPress cargará automáticamente jQuery si no se está cargando en el sitio.
  • $ ver - Este es el número de versión de nuestro script. Este parámetro no es obligatorio..
  • $ in_footer - Queremos cargar nuestro script en el pie de página, por lo que hemos establecido el valor como verdadero. Si desea cargar el script en el encabezado, entonces lo haría falso.

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

El último paso es usar el gancho de acción wp_enqueue_scripts para cargar el script. Como este es un código de ejemplo, lo hemos agregado justo debajo de todo lo demás.

Si estaba agregando esto a su tema o complemento, entonces puede colocar este gancho de acción donde realmente se requiere el script. Esto le permite reducir la huella de memoria de su complemento.

Ahora, algunos podrían preguntarse por qué vamos al paso adicional para registrar el script primero y luego ponerlo en cola. Bueno, esto permite que otros propietarios de sitios cancelen el registro de su secuencia de comandos sin modificar el código principal de su complemento.

Encolar correctamente los estilos en WordPress

Al igual que los scripts, también puedes poner en cola tus hojas de estilo. Mira el ejemplo de abajo:

 

En lugar de usar wp_enqueue_script , ahora estamos usando wp_enqueue_style para agregar nuestra hoja de estilo.

Tenga en cuenta que hemos utilizado wp_enqueue_scripts Gancho de acción para ambos estilos y scripts. A pesar del nombre, esta función funciona tanto para.

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

Sin embargo, si está utilizando la función de secuencias de comandos de puesta en cola en su tema, simplemente use get_template_directory_uri () en lugar. Si está trabajando con un tema infantil, utilice get_stylesheet_directory_uri () .

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

 

Esperamos que este artículo te haya ayudado a aprender cómo agregar correctamente jacvascript y estilos en WordPress. También es posible que desee estudiar el código fuente de los principales complementos de WordPress para ver algunos ejemplos de código de la vida real..

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