Page Details in the GTM dataLayer
Pushes page information (page type, post type, categories, author, publish date and login status) to the dataLayer before Google Tag Manager loads, for use in tags and triggers.
Opens WPIDE on
Code
add_action( 'wp_head', function () {
$data = array(
'pageType' => is_front_page() ? 'home' : ( is_singular() ? 'single' : ( is_archive() ? 'archive' : ( is_search() ? 'search' : ( is_404() ? '404' : 'other' ) ) ) ),
'loggedIn' => is_user_logged_in(),
);
if ( is_singular() ) {
$post = get_queried_object();
$data['postType'] = $post->post_type;
$data['postId'] = $post->ID;
$data['postAuthor'] = get_the_author_meta( 'display_name', $post->post_author );
$data['postDate'] = get_the_date( 'Y-m-d', $post );
$data['postCategories'] = wp_list_pluck( (array) get_the_category( $post->ID ), 'name' );
} elseif ( is_category() || is_tag() || is_tax() ) {
$data['termName'] = single_term_title( '', false );
$data['termTaxonomy'] = get_queried_object()->taxonomy;
}
echo '<script>window.dataLayer = window.dataLayer || []; window.dataLayer.push(' . wp_json_encode( $data ) . ");</script>\n";
}, 1 );
Notes
Create Data Layer Variables in GTM for the keys you need, for example pageType or postCategories.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.