Created
May 22, 2026 13:40
-
-
Save wp-seopress/0cfb39c634400e083d098bb1bee95aa6 to your computer and use it in GitHub Desktop.
Always send the parent product ID to Google Analytics 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * SEOPress PRO — Always send the parent product ID to Google Analytics 4. | |
| * | |
| * By default SEOPress sends the variation SKU (or, as fallback, the variation ID) | |
| * for each line item in a WooCommerce order. Some shops prefer to aggregate | |
| * analytics at the parent product level — e.g. a single "Blue T-Shirt" row in GA4 | |
| * instead of one row per size / color variation. This snippet returns the SKU | |
| * (or ID) of the parent product whenever a variation is purchased. | |
| * | |
| * Hook: seopress_gtag_ec_item_id | |
| * Plugin: SEOPress PRO 9.9+ | |
| * Requires: WooCommerce | |
| */ | |
| add_filter( 'seopress_gtag_ec_item_id', 'sp_gtag_ec_item_id', 10, 4 ); | |
| function sp_gtag_ec_item_id( $item_id, $product, $item, $order ) { | |
| if ( ! is_a( $product, 'WC_Product' ) ) { | |
| return $item_id; | |
| } | |
| // Only override for variations — keep the default for simple products. | |
| if ( ! $product->is_type( 'variation' ) ) { | |
| return $item_id; | |
| } | |
| $parent_id = $product->get_parent_id(); | |
| if ( ! $parent_id ) { | |
| return $item_id; | |
| } | |
| $parent = wc_get_product( $parent_id ); | |
| if ( ! is_a( $parent, 'WC_Product' ) ) { | |
| return $item_id; | |
| } | |
| return $parent->get_sku() ? $parent->get_sku() : $parent->get_id(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment