Skip to content

Inject gtm code conditionally #2167

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: trunk
Choose a base branch
from

Conversation

andreilupu
Copy link

Motivation for the change, related issues

Since WordPress Playground can be self-hosted, the GTM code should be configurable for those wanting to self-host.

The initial discussion was here

Implementation details

Sadly I found out that vite doesn't support if conditions .html templates so my initial implementation with <? if(...) ?> didn't work.

So what I did was:

  • Added a Vite plugin (vite-analytics-plugin.ts) that processes HTML files during build and injects the GTM code if a VITE_GOOGLE_ANALYTICS_ID .env variable is present.
  • Added an .env.example file and .gitignored the one that should be in production.
  • The plugin injects GTM code into the section of HTML files only if the variable is set
  • Build process remains silent by default but supports a --verbose flag for detailed logs
  • With the courtesy of Cursor AI I've added documentation with configuration instructions in CONFIGURATION.md
  • Plugin handles all HTML files including main index.html but also gutenberg.html and wordpress.html

Testing Instructions (or ideally a Blueprint)

  1. Create a .env.local file in packages/playground/website where you need to add a variable like this:
VITE_GOOGLE_ANALYTICS_ID=G-SVTNFCP8T7
  1. From the root of the project, build the website with the npm run build:website command.
  2. Now check the result in the dist/packages/playground/wasm-wordpress-net/index.html file. There, you should find the GTM code with the id you've inserted.
  3. You can also try with an empty VITE_GOOGLE_ANALYTICS_ID variable, or without a .env.local file. In this case, the GTM code should not be present.

This commit adds the ability to configure or disable Google Analytics
tracking in self-hosted WordPress Playground instances through environment
variables.

The implementation uses Vite's template syntax for conditional inclusion at
build time, ensuring no analytics code is included in the final HTML when
analytics is disabled.

Changes:
- Update index.html to use Vite template conditionals for Google Analytics
- Add .env and .env.example files with default configuration
- Add CONFIGURATION.md with documentation on available options
- Update .gitignore to handle local environment files properly
- Add reference to configuration options in README.md
Adds a Vite plugin that silently injects Google Tag Manager code into HTML
files during build when VITE_GOOGLE_ANALYTICS_ID is set. Plugin respects
--verbose flag for detailed logging and maintains clean HTML formatting.
const log = (msg: string, isError = false) => {
// Only log if it's an error or verbose mode is enabled
if (isError || verbose) {
isError ? console.error(msg) : console.log(msg);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: linter complains about the console statement. It is configured this way to enforce using the logger module in Playground code, but this is just a build script and the rule doesn't really apply. Feel free to silence this check for these lines of for the entire file.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. I've added the ignore rule for the entire file.

@adamziel
Copy link
Collaborator

Looks great, thank you! My only request would be to add a Playgwright E2E test in packages/playground/website/playwright/e2e/website-ui.spec.ts to make sure CI will tell us if and when this check breaks.

As for the current CI test failures – they are unrelated to this PR. trunk is affected by them, too. I have a fix for the PHP failures and I know @bgrgicak has one for the E2E failures – let's merge them some time soon.

@andreilupu
Copy link
Author

Hey @adamziel 👋

I've added a test for the default case, when the VITE_GOOGLE_ANALYTICS_ID constant is not present (which means no code should be printed).

I'm not sure if I can create a test that checks when the VITE_GOOGLE_ANALYTICS_ID is present. For that, I would have to create the .env.config file and run a build process once. As far as I understand, for this test setup, it is not possible?

@adamziel
Copy link
Collaborator

adamziel commented Apr 3, 2025

I'm away for the week so I'll defer to @bgrgicak for the answer and approval

Comment on lines +266 to +277
test('should not load GTM code when VITE_GOOGLE_ANALYTICS_ID is missing', async ({
website,
}) => {
await website.goto('./');

// By default, the VITE_GOOGLE_ANALYTICS_ID is not set, so GTM should not be loaded
// Check if GTM script is not present in the head
const gtmScript = await website.page
.locator('script[src*="googletagmanager.com"]')
.count();
expect(gtmScript).toBe(0);
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@andreilupu can we please add a test that confirms GTM is loaded, and window.gtag is defined, if the VITE_GOOGLE_ANALYTICS_ID environment variable is provided?

@bgrgicak
Copy link
Collaborator

bgrgicak commented Apr 7, 2025

Before we merge this PR we need to ensure the production Playground website builds with VITE_GOOGLE_ANALYTICS_ID=G-SVTNFCP8T7.

@andreilupu we should be able to do this by adding the VITE_GOOGLE_ANALYTICS_ID environment variable to the Build website action.

It's not sensitive info, so adding it to the .yml file seems ok.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Inbox
Development

Successfully merging this pull request may close these issues.

3 participants