-
Notifications
You must be signed in to change notification settings - Fork 50
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
feat(analytics): automatically link GA4 with Site Kit #1698
Changes from all commits
8447ef4
4768ceb
1475b3c
5885ce2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
<?php | ||
/** | ||
* Google Site Kit integration class. | ||
* | ||
* @package Newspack | ||
*/ | ||
|
||
namespace Newspack; | ||
|
||
use Google\Site_Kit\Context; | ||
|
||
defined( 'ABSPATH' ) || exit; | ||
|
||
/** | ||
* Main class. | ||
*/ | ||
class GoogleSiteKit { | ||
const GA4_SETUP_DONE_OPTION_NAME = 'newspack_analytics_has_set_up_ga4'; | ||
|
||
/** | ||
* Initialize hooks and filters. | ||
*/ | ||
public static function init() { | ||
add_action( 'admin_init', [ __CLASS__, 'setup_sitekit_ga4' ] ); | ||
add_action( 'wp_footer', [ __CLASS__, 'insert_ga4_analytics' ] ); | ||
} | ||
|
||
/** | ||
* Add GA4 analytics pageview reporting to AMP pages. | ||
*/ | ||
public static function insert_ga4_analytics() { | ||
if ( ! function_exists( 'is_amp_endpoint' ) || ! is_amp_endpoint() ) { | ||
return; | ||
} | ||
$sitekit_ga4_settings = self::get_sitekit_ga4_settings(); | ||
if ( false === $sitekit_ga4_settings || ! $sitekit_ga4_settings['useSnippet'] || ! isset( $sitekit_ga4_settings['measurementID'] ) ) { | ||
return; | ||
} | ||
$ga4_measurement_id = $sitekit_ga4_settings['measurementID']; | ||
// See https://github.com/analytics-debugger/google-analytics-4-for-amp. | ||
$config_path = Newspack::plugin_url() . '/includes/raw_assets/ga4.json'; | ||
|
||
?> | ||
<amp-analytics type="googleanalytics" config="<?php echo esc_attr( $config_path ); ?>" data-credentials="include"> | ||
<script type="application/json"> | ||
{ | ||
"vars": { | ||
"GA4_MEASUREMENT_ID": "<?php echo esc_attr( $ga4_measurement_id ); ?>", | ||
"DEFAULT_PAGEVIEW_ENABLED": true, | ||
"GOOGLE_CONSENT_ENABLED": false | ||
} | ||
} | ||
</script> | ||
</amp-analytics> | ||
<?php | ||
} | ||
|
||
/** | ||
* Get whether the current user is connected. | ||
* | ||
* @return bool Whether the user is connected to Google through Site Kit. | ||
*/ | ||
private static function is_user_connected() { | ||
global $wpdb; | ||
|
||
$user_id = get_current_user_id(); | ||
if ( ! $user_id ) { | ||
return false; | ||
} | ||
|
||
return ! empty( get_user_meta( $user_id, $wpdb->prefix . 'googlesitekit_site_verified_meta', true ) ); | ||
} | ||
|
||
/** | ||
* Get the name of the option under which Site Kit's GA4 settings are stored. | ||
*/ | ||
private static function get_sitekit_ga4_settings_option_name() { | ||
if ( class_exists( '\Google\Site_Kit\Modules\Analytics_4\Settings' ) ) { | ||
return \Google\Site_Kit\Modules\Analytics_4\Settings::OPTION; | ||
} | ||
return false; | ||
} | ||
|
||
/** | ||
* Get Site Kit's GA4 settings. | ||
*/ | ||
private static function get_sitekit_ga4_settings() { | ||
$option_name = self::get_sitekit_ga4_settings_option_name(); | ||
if ( false === $option_name ) { | ||
return false; | ||
} | ||
return get_option( $option_name, false ); | ||
} | ||
|
||
/** | ||
* Fetch data for the GA account data and set up GA4. | ||
*/ | ||
public static function setup_sitekit_ga4() { | ||
if ( ! class_exists( 'Google\Site_Kit\Core\Modules\Module' ) ) { | ||
return; | ||
} | ||
require_once NEWSPACK_ABSPATH . 'includes/plugins/google-site-kit/class-googlesitekitanalytics.php'; | ||
|
||
if ( ! self::is_user_connected() ) { | ||
return; | ||
} | ||
if ( get_option( self::GA4_SETUP_DONE_OPTION_NAME, false ) ) { | ||
return; | ||
} | ||
|
||
$sitekit_ga4_settings = self::get_sitekit_ga4_settings(); | ||
if ( false !== $sitekit_ga4_settings && $sitekit_ga4_settings['useSnippet'] && isset( $sitekit_ga4_settings['measurementID'] ) ) { | ||
return; | ||
} | ||
|
||
if ( ! defined( 'GOOGLESITEKIT_PLUGIN_MAIN_FILE' ) ) { | ||
return; | ||
} | ||
|
||
$sitekit_ga_settings = get_option( \Google\Site_Kit\Modules\Analytics\Settings::OPTION, false ); | ||
if ( false === $sitekit_ga_settings || ! isset( $sitekit_ga_settings['accountID'] ) ) { | ||
return; | ||
} | ||
$account_id = $sitekit_ga_settings['accountID']; | ||
|
||
try { | ||
$newspack_ga = new GoogleSiteKitAnalytics( new Context( GOOGLESITEKIT_PLUGIN_MAIN_FILE ) ); | ||
$ga4_settings = $newspack_ga->get_ga4_settings( $account_id ); | ||
if ( false === $ga4_settings ) { | ||
return; | ||
} | ||
$ga4_settings['ownerID'] = get_current_user_id(); | ||
$ga4_settings['useSnippet'] = true; | ||
|
||
$sitekit_ga4_option_name = self::get_sitekit_ga4_settings_option_name(); | ||
Logger::log( 'Updating Site Kit GA4 settings option.' ); | ||
update_option( self::GA4_SETUP_DONE_OPTION_NAME, true, true ); | ||
update_option( $sitekit_ga4_option_name, $ga4_settings, true ); | ||
} catch ( \Throwable $e ) { | ||
Logger::log( 'Failed updating Site Kit GA4 settings option: ' . $e->getMessage() ); | ||
} | ||
} | ||
} | ||
GoogleSiteKit::init(); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
<?php | ||
/** | ||
* Google Site Kit integration class. | ||
* | ||
* @package Newspack | ||
*/ | ||
|
||
namespace Newspack; | ||
|
||
use Google\Site_Kit\Context; | ||
use Google\Site_Kit\Modules\Analytics_4; | ||
use Google\Site_Kit\Modules\Analytics_4\Settings; | ||
use Google\Site_Kit\Core\Modules\Module; | ||
use Google\Site_Kit\Core\Authentication\Clients\Google_Site_Kit_Client; | ||
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin as Google_Service_GoogleAnalyticsAdmin; | ||
|
||
defined( 'ABSPATH' ) || exit; | ||
|
||
/** | ||
* Class extending Site Kit's Module, in order to easily access GA data via | ||
* Site Kit's Analytics Admin service. | ||
*/ | ||
class GoogleSiteKitAnalytics extends Module { | ||
public function register() { // phpcs:ignore Squiz.Commenting.FunctionComment.Missing | ||
return true; | ||
} | ||
public function setup_info() { // phpcs:ignore Squiz.Commenting.FunctionComment.Missing | ||
return true; | ||
} | ||
|
||
/** | ||
* Set up the Analytics Admin service, so the module can use it. | ||
* | ||
* @param Google_Site_Kit_Client $client Google client instance. | ||
*/ | ||
protected function setup_services( Google_Site_Kit_Client $client ) { | ||
return array( | ||
'analyticsadmin' => new Google_Service_GoogleAnalyticsAdmin( $client ), | ||
); | ||
} | ||
|
||
/** | ||
* Return data needed to set up Site Kit's GA4 settings. | ||
* | ||
* @param string $account_id Account ID. | ||
*/ | ||
public function get_ga4_settings( $account_id ) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I worry this method, executed on This could have There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good idea, done in 5885ce2 |
||
$analyticsadmin = $this->get_service( 'analyticsadmin' ); | ||
$properties_response = $analyticsadmin->properties->listProperties( | ||
array( | ||
'filter' => 'parent:accounts/' . $account_id, | ||
) | ||
); | ||
// Only proceed if there is exactly one GA4 property - otherwise we don't | ||
// know which to pick. | ||
if ( 1 !== count( $properties_response['properties'] ) ) { | ||
return false; | ||
} | ||
$property = $properties_response['properties'][0]; | ||
$datastreams_response = $analyticsadmin | ||
->properties_dataStreams // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase | ||
->listPropertiesDataStreams( | ||
$property['name'] | ||
); | ||
// Only proceed if there is one GA4 data stream - otherwise we don't | ||
// know which to pick. | ||
if ( 1 !== count( $datastreams_response['dataStreams'] ) ) { | ||
return false; | ||
} | ||
$datastream = $datastreams_response['dataStreams'][0]; | ||
preg_match( '/\d+$/', $property['name'], $property_id_matches ); | ||
$property_id = $property_id_matches[0]; | ||
preg_match( '/\d+$/', $datastream['name'], $webstreamdata_id_matches ); | ||
$webstreamdata_id = $webstreamdata_id_matches[0]; | ||
if ( ! $property_id || ! $webstreamdata_id ) { | ||
return false; | ||
} | ||
return [ | ||
'propertyID' => $property_id, | ||
'webDataStreamID' => $webstreamdata_id, | ||
'measurementID' => $datastream['webStreamData']['measurementId'], | ||
]; | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If Site Kit is not installed and active, it throws a fatal error. There should be a proper check before importing this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done in 4768ceb