You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在指定JavaScript代码中替换变量获取WordPress页面ID?

How to Get WordPress Page/Product ID for dataLayer

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 ProductID value in the dataLayer snippet—it should show a numeric ID instead of the static string.

内容的提问来源于stack exchange,提问作者Giovanni Rasulo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:23:01