When we talk about snippet we are talking about code fragments that we can insert in our WordPress to modify or add some function to our website. The most common when we talk about snippets is to associate them to PHP code snippets, but we can also associate them to other languages, such as CSS or JavaScript.
Usually they are only a few lines long, but we can extend them as much as we want. We could say that a plugin is a concatenation of snippets.
Focusing on PHP snippets, we can add them in three main ways:
- Adding it to the functions.php file of our theme. It is best to do this at the end of the theme.
- Mediante un plugin, como por ejemplo: Code Snippets,
- Creando un plugin de funciones personalizadas, como ya comenté en otro artículo.
Personally, whenever possible, I prefer the latter option and, as mentioned in the article I mention in the third option, better in a mu-plugin.
From there, the possibilities are endless, anything you can think of that you want to do, from preloading external DNS to adding Google Tag Manager scripts, Google Analytics .... or even adding an additional field to your product page in WooCommerce. Here, your imagination is the limit. Here are a couple of examples to give you an idea.
<?php
// Eliminar el numero de la versión de WordPress
remove_action('wp_head', 'wp_generator');
?>
<?php
/*
Plugin Name: Insertar Global Analytics en WordPress
Plugin URI: https://carlosmdh.es
Description: Plugin para insertar los Scripts de Global Analytics
Version: 1.0.1
Author: carlosmdh
License: GPL 2+
License URI:https://carlosmdh.es
*/
// Añadir el código de Global Analytics en el <head>
add_action( 'wp_head', 'carlosmdh_global_analytics' );
function carlosmdh_global_analytics() { ?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=INSERTA AQUI EL IDENTIFICADOR DE TU PROPIEDAD DE ANALYTICS"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'INSERTA AQUI EL IDENTIFICADOR DE TU PROPIEDAD DE UNIVERSAL ANALYTICS UA-XXXXXXXXX-Y', { 'anonymize_ip': true }); // Identificador de Google Analytics 3 (Universal Analytics
gtag('config', 'INSERTA AQUI EL IDENTIFICADOR DE TU PROPIEDAD DE GA4 G-XXXXXXXXXX'); //Identificador de Google Analytics 4 (GA4)
</script>
<!--End Global site tag (gtag.js) - Google Analytics -->
<?php }
?>
Don't go yet
I invite you to leave your impressions and/or doubts in the contact form and to suggest new topics that you would like me to cover in these tutorials. I will be happy to answer you by email and write in this blog.