Plugin pour ajouter Google tag manager

Written by

<?php
/**
 * Plugin Name: NG1 Google Tag Manager
 * Plugin URI: https://www.example.com/
 * Description: Un plugin pour insérer Google Tag Manager dans votre site WordPress.
 * Version: 1.0
 * Author: GEHIN Nicolas
 * Author URI: https://www.example.com/
 */

class Ng1GoogleTagManager {
    // Identifiant Google Tag Manager
    private $gtm_id;

    // Constructeur de la classe
    public function __construct($gtm_id) {
        $this->gtm_id = $gtm_id;

        // Action pour ajouter le code dans le header
        add_action('wp_head', array($this, 'insert_google_tag_manager'));

        // Action pour ajouter le code après la balise d'ouverture du body
        add_action('wp_body_open', array($this, 'insert_google_tag_manager_body'));
    }

    // Fonction pour ajouter le code Google Tag Manager dans le header
    public function insert_google_tag_manager() {
        ?>
        <!-- Début du code Google Tag Manager -->
        <script>(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','<?php echo $this->gtm_id; ?>');</script>
        <!-- Fin du code Google Tag Manager -->
        <?php
    }

    // Fonction pour ajouter le code Google Tag Manager après la balise d'ouverture du body
    public function insert_google_tag_manager_body() {
        ?>
        <!-- Google Tag Manager (noscript) -->
        <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=<?php echo $this->gtm_id; ?>"
        height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
        <!-- End Google Tag Manager (noscript) -->
        <?php
    }
}

// Identifiant Google Tag Manager
$gtm_id = 'VOTRE_ID_GTM';

// Instanciation de la classe Ng1GoogleTagManager avec l'identifiant Google Tag Manager
new Ng1GoogleTagManager($gtm_id);