如何在指定JavaScript代码中替换变量获取WordPress页面ID?
Hey there! To get the WordPress page/product ID in your dataLayer snippet, you'll need to replace the static 'ProductID' string with a WordPress PHP function that retrieves the current post/page ID. Here's how to do it properly:
1. Directly in Your Theme Template File
If you're adding this script directly to a WordPress template file (like single.php, page.php, header.php, or your WooCommerce product template), use the get_the_ID() function. This function returns the ID of the current post/page/product in the main query:
<script type="text/javascript"> dataLayer = dataLayer || []; dataLayer.push({ 'PageType': 'ProductPage', 'email': '', 'ProductID': '<?php echo get_the_ID(); ?>' }); </script>
Quick Notes:
get_the_ID()works both inside and outside the WordPress loop for the main query, so it’ll correctly pull the ID of the page/product being viewed.- If you’re working with a custom post type (like WooCommerce products), this function still returns the correct post ID, which matches what you need for
ProductID.
2. Using a Theme Function (Cleaner Approach)
If you want to keep your template files tidy, you can hook the script into WordPress' wp_head action via your theme's functions.php file. This also lets you target specific page types (like only product pages):
function add_datalayer_with_product_id() { // Target only WooCommerce product pages (use is_page() for regular pages) if ( is_product() ) { ?> <script type="text/javascript"> dataLayer = dataLayer || []; dataLayer.push({ 'PageType': 'ProductPage', 'email': '', 'ProductID': '<?php echo get_the_ID(); ?>' }); </script> <?php } } add_action( 'wp_head', 'add_datalayer_with_product_id' );
Key Reminders:
- Make sure your script is placed in a file that WordPress parses as PHP (not a static HTML file), since we’re using PHP to output the dynamic ID.
- To verify it’s working, view your page source and check the
ProductIDvalue in the dataLayer snippet—it should show a numeric ID instead of the static string.
内容的提问来源于stack exchange,提问作者Giovanni Rasulo

