tigerstyle-heat/includes/modules/class-google-setup.php
Ryan Malloy 0028738e33 Initial commit: TigerStyle Heat v2.0.0
Make your WordPress site irresistible. Natural SEO attraction with:
- robots.txt management
- sitemap.xml generation
- LLMs.txt support
- Google integration (Analytics, Search Console, Tag Manager)
- Schema.org structured data
- Open Graph / Twitter Card meta tags
- AMP support
- Visual elements gallery
- Built-in backup/restore module

Includes build.sh and .distignore for WordPress-installable release ZIPs.
2026-05-27 13:41:35 -06:00

619 lines
27 KiB
PHP

<?php
/**
* Google Setup Module for TigerStyle Heat
*
* Handles Google Analytics, Google Search Console, Google Tag Manager,
* and other Google service integrations
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
class TigerStyleSEO_Google_setup {
/**
* Single instance
*/
private static $instance = null;
/**
* Get instance
*/
public static function instance() {
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct() {
$this->init();
}
/**
* Initialize the module
*/
private function init() {
// Frontend hooks for injecting tracking codes
add_action('wp_head', array($this, 'inject_google_analytics'), 2);
add_action('wp_head', array($this, 'inject_google_tag_manager_head'), 1);
add_action('wp_body_open', array($this, 'inject_google_tag_manager_body'));
add_action('wp_head', array($this, 'inject_site_verification'), 3);
// Admin hooks
if (is_admin()) {
add_action('admin_post_update_google_setup', array($this, 'handle_form_submission'));
}
}
/**
* Handle form submission
*/
public function handle_form_submission() {
// Verify nonce
if (!wp_verify_nonce($_POST['google_setup_nonce'], 'update_google_setup')) {
wp_die(__('Security check failed', 'tigerstyle-heat'));
}
// Check permissions
if (!current_user_can('manage_options')) {
wp_die(__('You do not have sufficient permissions', 'tigerstyle-heat'));
}
// Sanitize and save settings
$google_analytics_id = sanitize_text_field($_POST['google_analytics_id'] ?? '');
$google_tag_manager_id = sanitize_text_field($_POST['google_tag_manager_id'] ?? '');
$google_site_verification = sanitize_text_field($_POST['google_site_verification'] ?? '');
$adsense_publisher_id = sanitize_text_field($_POST['adsense_publisher_id'] ?? '');
$google_my_business_id = sanitize_text_field($_POST['google_my_business_id'] ?? '');
// Enhanced ecommerce settings
$enhanced_ecommerce = isset($_POST['enhanced_ecommerce']) ? 1 : 0;
$track_outbound_links = isset($_POST['track_outbound_links']) ? 1 : 0;
$track_downloads = isset($_POST['track_downloads']) ? 1 : 0;
// Update options
update_option('google_analytics_id', $google_analytics_id);
update_option('google_tag_manager_id', $google_tag_manager_id);
update_option('google_site_verification', $google_site_verification);
update_option('adsense_publisher_id', $adsense_publisher_id);
update_option('google_my_business_id', $google_my_business_id);
update_option('google_enhanced_ecommerce', $enhanced_ecommerce);
update_option('google_track_outbound_links', $track_outbound_links);
update_option('google_track_downloads', $track_downloads);
// Redirect with success message
wp_redirect(admin_url('admin.php?page=tigerstyle-heat&message=google_setup_updated'));
exit;
}
/**
* Inject Google Analytics tracking code
* Now with TigerStyle Whiskers consent awareness! 🐱
*/
public function inject_google_analytics() {
$analytics_id = get_option('google_analytics_id', '');
if (empty($analytics_id)) {
return;
}
// Check TigerStyle Whiskers consent status
if (!$this->has_analytics_consent()) {
// Inject consent-conditional loading
$this->inject_consent_conditional_analytics($analytics_id);
return;
}
// Check if it's GA4 or Universal Analytics
if (strpos($analytics_id, 'G-') === 0) {
// GA4 implementation
$this->inject_ga4_tracking($analytics_id);
} elseif (strpos($analytics_id, 'UA-') === 0) {
// Universal Analytics implementation (legacy)
$this->inject_universal_analytics($analytics_id);
}
}
/**
* Inject GA4 tracking code
*/
private function inject_ga4_tracking($analytics_id) {
$enhanced_ecommerce = get_option('google_enhanced_ecommerce', 0);
$track_outbound = get_option('google_track_outbound_links', 0);
$track_downloads = get_option('google_track_downloads', 0);
echo "\n<!-- Google Analytics GA4 by TigerStyle Heat -->\n";
echo '<script async src="https://www.googletagmanager.com/gtag/js?id=' . esc_attr($analytics_id) . '"></script>' . "\n";
echo '<script>' . "\n";
echo 'window.dataLayer = window.dataLayer || [];' . "\n";
echo 'function gtag(){dataLayer.push(arguments);}' . "\n";
echo 'gtag("js", new Date());' . "\n";
// Basic configuration
$config_params = array();
if ($enhanced_ecommerce) {
$config_params[] = 'enhanced_conversions: true';
}
$config_string = !empty($config_params) ? ', {' . implode(', ', $config_params) . '}' : '';
echo 'gtag("config", "' . esc_attr($analytics_id) . '"' . $config_string . ');' . "\n";
// Outbound link tracking
if ($track_outbound) {
echo $this->get_outbound_link_tracking_script();
}
// Download tracking
if ($track_downloads) {
echo $this->get_download_tracking_script();
}
echo '</script>' . "\n";
echo "<!-- End Google Analytics GA4 -->\n";
}
/**
* Inject Universal Analytics tracking code (legacy)
*/
private function inject_universal_analytics($analytics_id) {
echo "\n<!-- Google Universal Analytics by TigerStyle Heat -->\n";
echo '<script async src="https://www.google-analytics.com/analytics.js"></script>' . "\n";
echo '<script>' . "\n";
echo 'window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;' . "\n";
echo 'ga("create", "' . esc_attr($analytics_id) . '", "auto");' . "\n";
if (get_option('google_enhanced_ecommerce', 0)) {
echo 'ga("require", "ec");' . "\n";
}
echo 'ga("send", "pageview");' . "\n";
echo '</script>' . "\n";
echo "<!-- End Google Universal Analytics -->\n";
}
/**
* Check if user has given analytics consent via TigerStyle Whiskers
*/
private function has_analytics_consent() {
// Check if TigerStyle Whiskers is active
if (!class_exists('TigerStyleWhiskers') && !class_exists('TigerStyleWhiskers_CookieConsent')) {
// Whiskers not active, allow analytics (backward compatibility)
return true;
}
// Check cookie consent directly from cookie
if (isset($_COOKIE['tigerstyle_whiskers_consent'])) {
$consent_data = json_decode(stripslashes($_COOKIE['tigerstyle_whiskers_consent']), true);
return isset($consent_data['analytics']) && $consent_data['analytics'] === true;
}
// Check via Whiskers API if available
if (class_exists('TigerStyleWhiskers_CookieConsent')) {
return TigerStyleWhiskers_CookieConsent::instance()->has_analytics_consent();
}
// Default to no consent if Whiskers is active but no consent given
return false;
}
/**
* Inject consent-conditional analytics that loads when consent is granted
*/
private function inject_consent_conditional_analytics($analytics_id) {
echo "\n<!-- TigerStyle Heat + Whiskers: Consent-Conditional Analytics -->\n";
echo '<script>' . "\n";
echo 'window.tigerstyleHeatAnalyticsId = "' . esc_attr($analytics_id) . '";' . "\n";
echo 'window.tigerstyleHeatAnalyticsConfig = {' . "\n";
// Pass through Heat configuration
$enhanced_ecommerce = get_option('google_enhanced_ecommerce', 0);
$track_outbound = get_option('google_track_outbound_links', 0);
$track_downloads = get_option('google_track_downloads', 0);
echo ' enhanced_ecommerce: ' . ($enhanced_ecommerce ? 'true' : 'false') . ',' . "\n";
echo ' track_outbound_links: ' . ($track_outbound ? 'true' : 'false') . ',' . "\n";
echo ' track_downloads: ' . ($track_downloads ? 'true' : 'false') . "\n";
echo '};' . "\n";
// Function to initialize analytics when consent is given
echo '
// TigerStyle Heat Analytics Initialization Function
window.tigerstyleHeatInitAnalytics = function() {
if (window.tigerstyleHeatAnalyticsLoaded) return; // Prevent double loading
var analyticsId = window.tigerstyleHeatAnalyticsId;
var config = window.tigerstyleHeatAnalyticsConfig;
console.log("🔥 TigerStyle Heat: Initializing analytics with user consent!");
// Load gtag script
var script = document.createElement("script");
script.async = true;
script.src = "https://www.googletagmanager.com/gtag/js?id=" + analyticsId;
document.head.appendChild(script);
// Initialize dataLayer and gtag
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag("js", new Date());
// Configure GA4
var configParams = {};
if (config.enhanced_ecommerce) {
configParams.enhanced_conversions = true;
}
gtag("config", analyticsId, configParams);
// Add tracking features based on Heat configuration
if (config.track_outbound_links) {
' . $this->get_outbound_link_tracking_script() . '
}
if (config.track_downloads) {
' . $this->get_download_tracking_script() . '
}
// Mark as loaded
window.tigerstyleHeatAnalyticsLoaded = true;
// Fire event for other plugins
if (typeof window.CustomEvent === "function") {
document.dispatchEvent(new CustomEvent("tigerstyleHeatAnalyticsInitialized", {
detail: { analyticsId: analyticsId, config: config }
}));
}
};
// Listen for Whiskers consent changes
document.addEventListener("tigerstyleWhiskersConsentChanged", function(event) {
if (event.detail && event.detail.analytics === true) {
console.log("🐱 TigerStyle Whiskers: Analytics consent granted, initializing Heat analytics!");
window.tigerstyleHeatInitAnalytics();
}
});
// Check if consent already exists on page load
if (window.tigerstyleWhiskersConsent && window.tigerstyleWhiskersConsent.hasAnalyticsConsent()) {
console.log("🔥 TigerStyle Heat: Existing analytics consent detected, initializing!");
window.tigerstyleHeatInitAnalytics();
}
';
echo '</script>' . "\n";
echo "<!-- End TigerStyle Heat + Whiskers Integration -->\n";
}
/**
* Inject Google Tag Manager head code
*/
public function inject_google_tag_manager_head() {
$gtm_id = get_option('google_tag_manager_id', '');
if (empty($gtm_id)) {
return;
}
echo "\n<!-- Google Tag Manager by TigerStyle Heat -->\n";
echo '<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':' . "\n";
echo 'new Date().getTime(),event:\'gtm.js\'});var f=d.getElementsByTagName(s)[0],' . "\n";
echo 'j=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\';j.async=true;j.src=' . "\n";
echo '\'https://www.googletagmanager.com/gtm.js?id=\'+i+dl;f.parentNode.insertBefore(j,f);' . "\n";
echo '})(window,document,\'script\',\'dataLayer\',\'' . esc_attr($gtm_id) . '\');</script>' . "\n";
echo "<!-- End Google Tag Manager -->\n";
}
/**
* Inject Google Tag Manager body code
*/
public function inject_google_tag_manager_body() {
$gtm_id = get_option('google_tag_manager_id', '');
if (empty($gtm_id)) {
return;
}
echo "\n<!-- Google Tag Manager (noscript) by TigerStyle Heat -->\n";
echo '<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=' . esc_attr($gtm_id) . '"' . "\n";
echo 'height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>' . "\n";
echo "<!-- End Google Tag Manager (noscript) -->\n";
}
/**
* Inject Google Site Verification meta tag
*/
public function inject_site_verification() {
$verification_code = get_option('google_site_verification', '');
if (empty($verification_code)) {
return;
}
echo '<meta name="google-site-verification" content="' . esc_attr($verification_code) . '" />' . "\n";
}
/**
* Get outbound link tracking script
*/
private function get_outbound_link_tracking_script() {
return '
// Outbound link tracking
document.addEventListener("click", function(e) {
var link = e.target.closest("a");
if (link && link.hostname !== window.location.hostname) {
gtag("event", "click", {
event_category: "outbound",
event_label: link.href,
transport_type: "beacon"
});
}
});
';
}
/**
* Get download tracking script
*/
private function get_download_tracking_script() {
return '
// Download tracking
document.addEventListener("click", function(e) {
var link = e.target.closest("a");
if (link && link.href) {
var filePath = link.pathname;
var fileExtension = filePath.split(".").pop().toLowerCase();
var downloadExtensions = ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "zip", "rar", "mp3", "mp4", "avi", "mov"];
if (downloadExtensions.includes(fileExtension)) {
gtag("event", "file_download", {
event_category: "downloads",
event_label: link.href,
value: 1
});
}
}
});
';
}
/**
* Render admin page
*/
public function render_admin_page() {
// Get current settings
$analytics_id = get_option('google_analytics_id', '');
$gtm_id = get_option('google_tag_manager_id', '');
$site_verification = get_option('google_site_verification', '');
$adsense_id = get_option('adsense_publisher_id', '');
$business_id = get_option('google_my_business_id', '');
$enhanced_ecommerce = get_option('google_enhanced_ecommerce', 0);
$track_outbound = get_option('google_track_outbound_links', 0);
$track_downloads = get_option('google_track_downloads', 0);
?>
<div class="seo-info-box">
<h3><?php _e('Google Services Integration', 'tigerstyle-heat'); ?></h3>
<p class="description">
<?php _e('Connect your website with essential Google services for better SEO performance and analytics. This includes Google Analytics, Google Search Console, Google Tag Manager, and AdSense integration.', 'tigerstyle-heat'); ?>
</p>
<?php if (class_exists('TigerStyleWhiskers') || class_exists('TigerStyleWhiskers_CookieConsent')): ?>
<div style="background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%); color: white; padding: 15px; border-radius: 8px; margin-top: 15px;">
<strong>🐱 TigerStyle Whiskers Integration Active!</strong><br>
<small>Analytics will automatically respect user privacy consent. Users must grant analytics consent before Google Analytics loads, ensuring GDPR compliance.</small>
</div>
<?php endif; ?>
</div>
<form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
<input type="hidden" name="action" value="update_google_setup">
<?php wp_nonce_field('update_google_setup', 'google_setup_nonce'); ?>
<h2><?php _e('Analytics & Tracking', 'tigerstyle-heat'); ?></h2>
<table class="form-table">
<tr>
<th scope="row">
<label for="google_analytics_id"><?php _e('Google Analytics ID', 'tigerstyle-heat'); ?></label>
</th>
<td>
<input
type="text"
id="google_analytics_id"
name="google_analytics_id"
value="<?php echo esc_attr($analytics_id); ?>"
placeholder="G-XXXXXXXXXX or UA-XXXXXXXX-X"
class="regular-text"
>
<p class="description">
<?php _e('Enter your Google Analytics tracking ID. Use GA4 format (G-XXXXXXXXXX) for new properties or Universal Analytics format (UA-XXXXXXXX-X) for legacy properties.', 'tigerstyle-heat'); ?>
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="google_tag_manager_id"><?php _e('Google Tag Manager ID', 'tigerstyle-heat'); ?></label>
</th>
<td>
<input
type="text"
id="google_tag_manager_id"
name="google_tag_manager_id"
value="<?php echo esc_attr($gtm_id); ?>"
placeholder="GTM-XXXXXXX"
class="regular-text"
>
<p class="description">
<?php _e('Enter your Google Tag Manager container ID (GTM-XXXXXXX). Note: This will override individual tracking codes if both are configured.', 'tigerstyle-heat'); ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><?php _e('Enhanced Tracking', 'tigerstyle-heat'); ?></th>
<td>
<fieldset>
<label>
<input type="checkbox" name="enhanced_ecommerce" value="1" <?php checked($enhanced_ecommerce); ?>>
<?php _e('Enable Enhanced Ecommerce tracking', 'tigerstyle-heat'); ?>
</label><br>
<label>
<input type="checkbox" name="track_outbound_links" value="1" <?php checked($track_outbound); ?>>
<?php _e('Track outbound link clicks', 'tigerstyle-heat'); ?>
</label><br>
<label>
<input type="checkbox" name="track_downloads" value="1" <?php checked($track_downloads); ?>>
<?php _e('Track file downloads', 'tigerstyle-heat'); ?>
</label>
</fieldset>
<p class="description">
<?php _e('Enable additional tracking features for better analytics insights.', 'tigerstyle-heat'); ?>
</p>
</td>
</tr>
</table>
<h2><?php _e('Search Console & Verification', 'tigerstyle-heat'); ?></h2>
<table class="form-table">
<tr>
<th scope="row">
<label for="google_site_verification"><?php _e('Google Site Verification', 'tigerstyle-heat'); ?></label>
</th>
<td>
<input
type="text"
id="google_site_verification"
name="google_site_verification"
value="<?php echo esc_attr($site_verification); ?>"
placeholder="aBcDeFgHiJkLmNoPqRsTuVwXyZ123456789"
class="regular-text"
>
<p class="description">
<?php _e('Enter your Google Search Console verification code (content value from meta tag). This enables your site in Google Search Console.', 'tigerstyle-heat'); ?>
</p>
</td>
</tr>
</table>
<h2><?php _e('Other Google Services', 'tigerstyle-heat'); ?></h2>
<table class="form-table">
<tr>
<th scope="row">
<label for="adsense_publisher_id"><?php _e('AdSense Publisher ID', 'tigerstyle-heat'); ?></label>
</th>
<td>
<input
type="text"
id="adsense_publisher_id"
name="adsense_publisher_id"
value="<?php echo esc_attr($adsense_id); ?>"
placeholder="pub-XXXXXXXXXXXXXXXX"
class="regular-text"
>
<p class="description">
<?php _e('Enter your Google AdSense Publisher ID for auto ads integration.', 'tigerstyle-heat'); ?>
</p>
</td>
</tr>
<tr>
<th scope="row">
<label for="google_my_business_id"><?php _e('Google My Business ID', 'tigerstyle-heat'); ?></label>
</th>
<td>
<input
type="text"
id="google_my_business_id"
name="google_my_business_id"
value="<?php echo esc_attr($business_id); ?>"
placeholder="ChIJXXXXXXXXXXXXXXXXXXXXXX"
class="regular-text"
>
<p class="description">
<?php _e('Enter your Google My Business Place ID for local business integration.', 'tigerstyle-heat'); ?>
</p>
</td>
</tr>
</table>
<?php submit_button(__('Update Google Setup', 'tigerstyle-heat')); ?>
</form>
<div class="seo-info-box">
<h3><?php _e('Setup Instructions', 'tigerstyle-heat'); ?></h3>
<div class="seo-setup-steps">
<h4><?php _e('Google Analytics Setup:', 'tigerstyle-heat'); ?></h4>
<ol>
<li><?php _e('Visit <a href="https://analytics.google.com/" target="_blank">Google Analytics</a> and sign in', 'tigerstyle-heat'); ?></li>
<li><?php _e('Create a new GA4 property for your website', 'tigerstyle-heat'); ?></li>
<li><?php _e('Copy the Measurement ID (starts with G-) from the Data Streams section', 'tigerstyle-heat'); ?></li>
<li><?php _e('Paste the ID in the Google Analytics ID field above', 'tigerstyle-heat'); ?></li>
</ol>
<h4><?php _e('Google Search Console Setup:', 'tigerstyle-heat'); ?></h4>
<ol>
<li><?php _e('Visit <a href="https://search.google.com/search-console/" target="_blank">Google Search Console</a>', 'tigerstyle-heat'); ?></li>
<li><?php _e('Add your property using the URL prefix method', 'tigerstyle-heat'); ?></li>
<li><?php _e('Select "HTML tag" verification method', 'tigerstyle-heat'); ?></li>
<li><?php _e('Copy the content value from the meta tag (everything between the quotes after content=)', 'tigerstyle-heat'); ?></li>
<li><?php _e('Paste it in the Google Site Verification field above and save', 'tigerstyle-heat'); ?></li>
<li><?php _e('Return to Search Console and click "Verify"', 'tigerstyle-heat'); ?></li>
</ol>
<h4><?php _e('Google Tag Manager Setup:', 'tigerstyle-heat'); ?></h4>
<ol>
<li><?php _e('Visit <a href="https://tagmanager.google.com/" target="_blank">Google Tag Manager</a>', 'tigerstyle-heat'); ?></li>
<li><?php _e('Create a new container for your website', 'tigerstyle-heat'); ?></li>
<li><?php _e('Copy the Container ID (GTM-XXXXXXX)', 'tigerstyle-heat'); ?></li>
<li><?php _e('Paste it in the Google Tag Manager ID field above', 'tigerstyle-heat'); ?></li>
</ol>
<h4><?php _e('Sitemap Submission:', 'tigerstyle-heat'); ?></h4>
<p><?php _e('Once Google Search Console is verified, submit your sitemap:', 'tigerstyle-heat'); ?></p>
<ol>
<li><?php _e('Go to Sitemaps in the left sidebar of Search Console', 'tigerstyle-heat'); ?></li>
<li><?php printf(__('Enter your sitemap URL: %s', 'tigerstyle-heat'), '<code>' . home_url('/sitemap.xml') . '</code>'); ?></li>
<li><?php _e('Click Submit to notify Google about your content', 'tigerstyle-heat'); ?></li>
</ol>
</div>
</div>
<?php if (!empty($analytics_id) || !empty($gtm_id) || !empty($site_verification)): ?>
<div class="seo-info-box">
<h3><?php _e('Current Configuration Status', 'tigerstyle-heat'); ?></h3>
<ul>
<?php if (!empty($analytics_id)): ?>
<li><strong><?php _e('Google Analytics:', 'tigerstyle-heat'); ?></strong>
<span style="color: green;">✓ Configured (<?php echo esc_html($analytics_id); ?>)</span>
</li>
<?php endif; ?>
<?php if (!empty($gtm_id)): ?>
<li><strong><?php _e('Google Tag Manager:', 'tigerstyle-heat'); ?></strong>
<span style="color: green;">✓ Configured (<?php echo esc_html($gtm_id); ?>)</span>
</li>
<?php endif; ?>
<?php if (!empty($site_verification)): ?>
<li><strong><?php _e('Site Verification:', 'tigerstyle-heat'); ?></strong>
<span style="color: green;">✓ Meta tag added</span>
</li>
<?php endif; ?>
<?php if (!empty($adsense_id)): ?>
<li><strong><?php _e('Google AdSense:', 'tigerstyle-heat'); ?></strong>
<span style="color: green;">✓ Configured (<?php echo esc_html($adsense_id); ?>)</span>
</li>
<?php endif; ?>
</ul>
</div>
<?php endif; ?>
<?php
}
}