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 instalar y configurar Google Tag Manager 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.

¿Desea instalar Google Tag Manager en WordPress?

Google Tag Manager le permite añadir fragmentos de código de seguimiento a su sitio web WordPress. Es una herramienta gratuita y le permite realizar un seguimiento de las diferentes interacciones de los usuarios.

En este artículo, le mostraremos cómo instalar y establecer correctamente Google Tag Manager en WordPress y le explicaremos sus ventajas.

how to install and setup Google Tag Manager in WordPress

¿Qué es Google Tag Manager?

Google Tag Manager (GTM) es una herramienta gratuita de Google que te permite añadir, actualizar y gestionar fragmentos de código denominados etiquetas en tu sitio de WordPress.

A menudo, los propietarios de sitios web necesitan añadir varios fragmentos de código para realizar un seguimiento de sus conversiones, envíos de formularios, clics en enlaces y recopilar otros datos analíticos en su sitio web. Con Google Tag Manager, puede añadir y gestionar fácilmente todas estas secuencias de comandos desde un único panel de control.

Hay plantillas de etiquetas integradas para Google Analytics, Google Ads, Google Optimize, DoubleClick y Google AdSense. Tag Manager también funciona con varias plataformas de análisis y seguimiento de terceros.

Esto le ahorra el tiempo de añadir y eliminar etiquetas de su código en lugar de gestionarlo desde un sencillo cuadro de mandos. Por no hablar de que todos estos fragmentos de código independientes se cargan en un solo script.

Dicho esto, vamos a ver cómo añadir Google Tag Manager a WordPress. También le mostraremos un método alternativo para el seguimiento de las diferentes interacciones de los usuarios en su sitio. Lo mejor de todo es que no tienes que editar código ni establecer etiquetas.

Sólo tiene que hacer clic en los enlaces siguientes para saltar a la sección que prefiera:

Añadir Google Tag Manager en WordPress

En primer lugar, tendrás que visitar el sitio web de Google Tag Manager y hacer clic en el botón “Comenzar gratis” para registrarte.

Google Tag Manager website

Después de acceder, llegará a la página de añadir nueva cuenta.

Siga adelante y haga clic en el botón “Crear cuenta”.

Create account in tag manager

A continuación, puede introducir un nombre para su cuenta y seleccionar un país en el menú desplegable.

Tag Manager también le dará la opción de compartir datos de forma anónima con Google. Solo tiene que hacer clic en la casilla de verificación y desplazarse hacia abajo.

Enter account name and country

Ahora tienes que añadir un contenedor a tu cuenta. Un contenedor puede ser un sitio web, aplicaciones iOS o Android, o un servidor. En este caso, utilizaremos la opción “Web”.

Puedes utilizar el dominio de tu sitio para el nombre del contenedor. Cuando hayas terminado, haz clic en el botón “Crear” para continuar.

Enter container name and select platform

Ahora verás que se desliza una nueva ventana desde la derecha con el acuerdo de términos de servicio de Google Tag Manager.

Puede hacer clic en la casilla de verificación de la parte inferior para aceptar las condiciones de tratamiento de datos y, a continuación, hacer clic en el botón “Sí” de la parte superior.

Accept tag manager terms of agreement

Google Tag Manager creará ahora su cuenta.

A continuación, le mostrará los códigos de seguimiento que debe añadir a su sitio.

Copy tag manager code

Simplemente copie estos 2 códigos, ya que tendrá que añadirlos a la cabecera y a la sección del cuerpo de su sitio web WordPress.

Añadir código de Google Tag Manager a WordPress

La forma más fácil de añadir fragmentos de código en WordPress es usar el plugin WPCode. Es el mejor plugin de fragmentos de código para WordPress y te permite añadir y gestionar diferentes códigos personalizados en tu sitio web.

Lo mejor es que puedes empezar gratis con WPCode. Sin embargo, también hay una versión premium que ofrece más características como una biblioteca de fragmentos de código, lógica condicional, fragmentos de inserción automática, y mucho más.

En primer lugar, tendrás que instalar y activar el plugin gratuito WPCode. Si necesitas ayuda, consulta nuestra guía sobre cómo instalar un plugin de WordPress.

Una vez activado, debe visitar la página Fragmentos de código ” Cabeceras y pies de página del panel de administrador de WordPress. A continuación, introduzca los códigos que ha copiado anteriormente.

Asegúrese de pegar el código <head> en el campo Cabecera y el código <body> en el campo Cuerpo, como puede ver a continuación.

Add header and body tag manager codes

Cuando hayas terminado, no olvides hacer clic en el botón “Guardar cambios”.

Google Tag Manager ya está listo para usarse en su sitio web WordPress.

Creación de una nueva etiqueta en Google Tag Manager

A continuación, puede crear una nueva etiqueta en Google Tag Manager y establecer el seguimiento en su sitio web de WordPress.

Supongamos que desea añadir Google Analytics 4 (GA4) a su sitio web WordPress mediante Tag Manager.

En primer lugar, deberá hacer clic en la opción “Añadir una nueva etiqueta” del panel de control de Tag Manager.

Create a new tag

A continuación, puede introducir un nombre para su etiqueta en la parte superior.

Desde aquí, basta con hacer clic en la opción “Configuración de etiquetas”.

Enter a title and click tag configuration

A continuación, Tag Manager le mostrará diferentes tipos de etiquetas entre los que elegir.

Por ejemplo, esto incluirá etiquetas para Google Analytics, Google Ads, Floodlight, etc. Seleccionaremos ‘Google Analytics: GA4 Configuration’ para este tutorial.

Select a tag type

A continuación, deberá introducir los datos de su etiqueta.

En primer lugar, puede añadir el ID de medida.

Enter measurement ID

Puede encontrar el ID de medición accediendo a su cuenta de Google Analytics.

Simplemente diríjase a la opción Admin ” Data Streams bajo la columna de Propiedades. Siga adelante y haga clic en sus Transmisiones de Datos para ver el ID de medición.

Select your data stream

Cuando se abra una nueva ventana, debería ver el ID de medida en la esquina superior derecha.

Basta con copiar la identificación.

Copy your Measurement ID

Ahora, vuelva a la ventana o pestaña de Google Tag Manager e introduzca el ID de medición.

A continuación, desplácese hacia abajo y haga clic en la opción “Activación”.

Add a trigger

Google Tag Manager mostrará ahora activadores integrados entre los que elegir.

Seleccione la opción “Inicialización – Todas las páginas”.

Select initialization all page trigger

Después de seleccionar el disparador, tendrás que guardar los ajustes.

Basta con hacer clic en el botón “Guardar” de la esquina superior derecha.

Save your GA4 tag

Ahora debería ver la etiqueta recién creada.

Haz clic en el botón “Enviar” para ejecutar la etiqueta.

Preview and submit your tag

Establecer un seguimiento avanzado con MonsterInsights (de forma sencilla)

Ahora que ya sabe cómo instalar y utilizar Google Tag Manager, puede utilizar una forma más sencilla de establecer un seguimiento avanzado en su sitio de WordPress.

Con MonsterInsights, no tienes que realizar complicadas configuraciones en GTM. Es el mejor plugin de Google Analytics para WordPress y configura automáticamente el seguimiento avanzado para usted. Usted también no tiene que preocuparse de cometer un error que podría estropear sus datos de seguimiento.

La mejor parte, MonsterInsights muestra informes dentro de su escritorio de WordPress. No tendrás que salir de tu sitio para ver su rendimiento. Presenta datos importantes para tu negocio y te ayuda a descubrir nuevas perspectivas.

Para este tutorial, utilizaremos la versión MonsterInsights Pro porque incluye características avanzadas de seguimiento y extensiones premium. También hay una versión MonsterInsights Lite que puede utilizar para empezar de forma gratuita.

En primer lugar, tendrá que instalar y activar el plugin MonsterInsights. Si necesita ayuda, consulte nuestra guía sobre cómo instalar un plugin de WordPress.

Una vez activado, verá la pantalla de bienvenida de MonsterInsights. Puede hacer clic en el botón “Iniciar el asistente” y seguir los pasos que aparecen en pantalla para configurar Google Analytics.

Launch setup wizard

Para obtener más información, consulte nuestra guía sobre cómo instalar Google Analytics en WordPress.

MonsterInsights trabajará fuera de la caja y añadirá automáticamente el seguimiento en Google Analytics.

Estas son algunas de las características de seguimiento que ofrece el plugin:

1. Seguimiento de los clics en enlaces y botones

MonsterInsights establece enlazar y hacer clic en el botón de seguimiento de clics fuera de la caja en su sitio web. Google Analytics no realiza un seguimiento de los clics en enlaces por defecto, y tendría que utilizar GTM para añadir el seguimiento.

Por ejemplo, puede hacer un seguimiento del rendimiento de los afiliados y ver en qué enlaces hacen más clic los usuarios. De este modo, puedes aumentar tus ingresos promocionando a los afiliados que reciben muchos clics.

Outbound and affiliate links report

Del mismo modo, el plugin también realiza un seguimiento de los clics en enlaces salientes. Estos son enlaces a otros sitios web en su sitio. Puedes utilizar estos datos para crear nuevas asociaciones, inscribirte en un programa de afiliados y crear nuevos contenidos en tu propio sitio.

Además, MonsterInsights también ayuda a realizar un seguimiento de los enlaces telefónicos, las descargas de archivos, los clics en los botones de llamada a la acción (CTA ), etc.

2. Establecer el seguimiento del comercio electrónico en WordPress

Si tienes una tienda online, MonsterInsights te ayuda a hacer un seguimiento de su rendimiento sin necesidad de editar el script de seguimiento o utilizar Google Tag Manager.

Ofrece una extensión de comercio electrónico que le permite activar el seguimiento del comercio electrónico en WordPress con sólo unos clics. Puede ver la tasa / tarifa de conversión general de su sitio, las transacciones, los ingresos, el valor medio de los pedidos, los productos más vendidos y mucho más.

Ecommerce overview report in MonsterInsights

Para más detalles, consulte nuestra guía sobre cómo establecer correctamente el seguimiento de comercio electrónico en WordPress.

3. Configurar el seguimiento de conversiones de formularios

Con MonsterInsights, también puede establecer el seguimiento de conversión de formul arios en Google Analytics. El plugin ofrece una extensión de formularios que realiza un seguimiento automático de los formularios de WordPress en su sitio.

Si utiliza Google Tag Manager, tendrá que crear etiquetas independientes para todos sus formularios y realizar un seguimiento de ellas en Google Analytics.

Sin embargo, MonsterInsights hace que este proceso sea muy sencillo. Además, puedes ver los datos dentro del escritorio de WordPress.

Forms report

4. Activar automáticamente el seguimiento de la profundidad del desplazamiento

¿Alguna vez se ha preguntado cuánto se desplaza la gente por su página web antes de abandonar el sitio? El seguimiento de la profundidad del desplazamiento muestra exactamente eso y le ayuda a colocar sus anuncios de banner y CTA en el lugar correcto para aumentar las conversiones.

MonsterInsights activa automáticamente el seguimiento de desplazamiento en su sitio web. No hay necesidad de configuración adicional utilizando Google Tag Manager o modificar el código de seguimiento en absoluto.

Scroll tracking

Puede leer nuestra guía sobre cómo añadir el seguimiento de la profundidad del desplazamiento en WordPress con Google Analytics.

Esperamos que este artículo te haya ayudado a aprender a instalar y establecer Google Tag Manager en WordPress. Puede que también quieras ver nuestra guía sobre la guía definitiva para WordPress SEO y el mejor software de chat en vivo para pequeñas empresas.

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

53 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. Moinuddin Waheed says

    Google tag manager aka GTM is such a powerful tool that enables tracking Google ads, Google analytics, Google optimize and Google Adsense all with the help of a snippet. This is really helpful in terms of tracking and making informed decision about different aspect of the blog and business.
    Both the methods mentioned is easy to implement and gets the GTM working for us. The second method with the plugin is better option for beginners like us. Thanks for bringing such an insightful article.

  3. prakhar sahu says

    as a beginner, this post was given to me from siteground guy to help me and thanks to you as well .thankyou

  4. Jasper says

    Hi there,

    This solution works as a charm, thanks a lot. I have 1 issue though: All the way at the bottom of all my site pages there is now a white bar with the text “Javascript” written inside it on the left side of the screen.

    How can I remove that?

    • WPBeginner Support says

      You may want to make sure you copied the entire code as that normally means javascript code you’ve added to your site may have an error.

      Administrador

  5. Ann says

    I’d rather not install more plugins than I need. My theme allows me to paste the GTM code with the GA tag in my header. However, how do I get the body code in my page? Do i just use a text field high up on my HOME page and paste it in there? Thanks!

    • Nitesh S says

      Hey Ann,

      I know I’m late to reply but I’d highly recommend you install the plugin.

      Without it, you won’t be able to send detailed information to GA. I.e. If it’s an eCommerce – you won’t be able to receive product information, GTM on it’s own will give you extremely basic data and you’ll need to configure it entirely yourself which believe me takes weeks!

  6. Naji Boutros says

    Google Tag manager specifically says to post a portion of the code in the body of the webpage. Nothing I find on implementing Google Tag manager addresses this. Why is that?

    • adrian says

      The video hasn’t been updated in a while. What you have to do is put the 2nd half of the code in the footer section of the plugin, which actually places it in the body section. If you look at the plugin in wordpress it says “These scripts will be printed above the tag.”

      Anything above ” is going to be in the body section.

  7. Deelip Kushwaha says

    Hi Admin,

    I don’t have good knowledge on WordPress.
    I am using WordPress theme for my website. And want to add google tag manager in my website. Can you please tell me how can I add tag manager code in WordPress Child theme. I am waiting for your positive response.

  8. NM says

    Where shoud I put “Additionally, paste this code immediately after the opening tag” on Header and Footer Plugin ?

  9. Aswani says

    Wonderful guide. I got one major confusion cleared now – whether to add google analytics code first and then add google tag manager tags. Thanks a lot for this awesome help. A big time saver.

  10. Rob Wood says

    Hi,

    There is two elements to Google Tag Manager install

    1) in Header
    2) in Body

    Will you update your explanation to show the solution for this?

  11. AJ says

    Also, there’s another piece of code besides the code you mention here. They ask you to “Paste this code as high in the of the page as possible:”, and the code is:


    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({‘gtm.start’:
    new Date().getTime(),event:’gtm.js’});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!=’dataLayer’?’&l=’+l:”;j.async=true;j.src=
    ‘https://www.googletagmanager.com/gtm.js?id=’+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,’script’,’dataLayer’,’GTM-XXXXXX’);

    Can I install both pieces of code in the header, right next to each other?

    Thanks!

    • Anthony says

      Yes, Google has changed this very recently. I want this also up-to-date and by Function.php instead of a plugin. Anybody???

  12. AJ says

    Hi, can I have both GA and GTM in the code at the same time? Or I have to remove GA if I’m installing GTM?

    Thanks!

    • Kevin says

      Hi AJ,

      you can have both (GA + GTM) in the code at the same time. No worries. Although it is more convenient to fire the GA snippet also through GTM. Google provides good instructions how to do that:

  13. Alessandro Marengo says

    Am I wrong or there is a bit of lack of support for your plugin on wordpress forum? It’s a pity… :(

  14. Murray says

    Great tutorial – I love you guys. I read it through and then read all the comments. Got my answers. Installed it etc and then checked my site by browsing from my smartphone.
    Everything is working great!

    No questions, just a big thankyou.
    Well done :)

  15. Gaurav Singh says

    I got This completely, But I have a confusion about there is my analytics code exist to how can I both through plugin insert header & Footer.

  16. Catherine says

    I’m very new to Google Tag Manager, this is the easiest tutorial I’ve found so far without the confusion.
    However I’m wondering if there is a conflict with having both GA code and GTM code on my website?
    There is a place on my wordpress theme to insert the Google Analytics code for tracking which I have always had.
    I have now inserted the Google Tag Manager code to the header php on my site so should I remove the original Google Analytics code or does that stay?
    Many Thanks,
    Catherine

  17. Lisa Smith says

    Thank you for making the plugin Multisite compatible!

    I see Google Tag Manager says to place the code immediately after the opening tag, but the plugin places it inside the tag. Will it still work if placed in the head rather than body?

  18. AJ Levinson says

    Thank you so much for this excellent tutorial.

    I am confused about a potential conflict with this method. Can you please help?

    Google Tag Manager says that the code can not be in the header. They want it right after the tag. But, if I use the Insert Headers and Footers plugin and paste the code there, won’t it put the Tag Manager code in the Header? Won’t this cause a conflict?

    In the paragraph, you wrote: “If you do not wish to install a plugin, then you can also add the Google Tag Manager code in your WordPress theme or Child theme. Simply edit the header.php template and paste the code right after tag.” Is there a step-by-step on how to do this?

    • Jason says

      You might have wondered why Google so forcefully recommends that you place the container snippet just after the opening tag. There are two good reasons to do so.

      First, if you add the tag as well (as you should), this should always be in the body of the document. The tag (which is shown for browsers without JavaScript enabled) contains an iFrame which loads the GTM library. If you add the tag into the head of your document, it can perform pretty wildly with some browsers. You could experiment with leaving the in the body, and placing the JavaScript in the , but I haven’t tested it and certainly don’t recommend it.

      The second reason is simple: to maximize data collection, the snippet should be the first thing loaded when the body of the page is rendered. Because the library is loaded asynchronously, there’s no reason to delay it at all. So have it load as the first thing when the body is rendered, so that you don’t risk losing any data due to sluggish DOM elements delaying the page load.

      • Vince Outlaw says

        So, if you want it to load right after the tag, then is seems like you can’t use the Insert Headers and Footers plugin because the only options are in the (nope) and right before the tag (so at the end of loading, nope).

        Am I reading this right?

  19. steve says

    Curious about duel installs, of both, on WordPress — I know you have to have both accounts setup in google, but does the tag manager, in effect, *replace* the GA plugin we’ve been using for a few years?

    Or, does one still install both the GA plugin AND the tag manager plugin? Seems redundant, or perhaps I’m not understanding things clearly.

    Just trying to know the most efficient way to get all the analytics I enjoy now, and all the tag manager analytics as well.

    Thanks,
    S

    • WPBeginner Support says

      Tag Manager is not an analytics solution in itself. It just provides an easier way to add analytics tracking in your WordPress site. If you add Google Analytics by adding it through a tag in tag manager than you can safely uninstall Google Analytics plugin on your WordPress site.

      Administrador

  20. Marcelo says

    Sorry i might be slower to understand, but what is the difference between google analytic and tag manager ? I mean, what am i missing using analytic only ?

  21. Susan Meko says

    What a detailed and step by step guide on GTM. I just completed my training on this and now I am completely clear on this.
    I believe it has nothing to do with SEO and ranking, it is just for managing all the tags we could us on our website.

    Regards
    Susan Meko

  22. Kabelo says

    Hi, may I ask. I have two wordpress installed in one domain. eg: http://www.wp1.com/wp2.

    Will tracking wp1 be able to give me the stats of w2. If not, how may I achieve that?

    Looking forward to your response.

    Thank you in advance.

  23. DOK Simon says

    That is great , simple tutorial with details. A friend told me about it but didn’t explain to this extent … Please apart from managing all script in a single dashboard does it in anyway improve the site SEO…. ??

  24. Saeed Khan says

    Brother your article is very informative. Can we used google analytics and google tag manager code together?

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.