You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

WordPress订单确认页配置GTM DataLayer遇致命错误求助

Fixing Fatal Errors When Adding GTM DataLayer to WooCommerce Thank You Page

Hey there! Let's figure out why you're hitting that fatal error and get your GTM DataLayer working smoothly.

What's Causing the Fatal Error?

The most likely culprit is how you're outputting the <script> tag in your PHP code. When you directly write <script> inside a PHP function without properly wrapping it as a string, the PHP parser gets confused—it thinks the < is part of PHP syntax instead of HTML. This triggers a syntax error that crashes your site.

Quick Fix: Use Heredoc/Nowdoc for Safe HTML Output

Heredoc syntax lets you write multi-line HTML/JS without worrying about escaping quotes or confusing PHP with HTML tags. Here's a working example you can add to your theme's functions.php or a code snippet plugin:

add_action( 'woocommerce_thankyou', 'load_gtm_datalayer_on_thankyou' );
function load_gtm_datalayer_on_thankyou( $order_id ) {
    // Fetch the order object
    $order = wc_get_order( $order_id );
    if ( ! $order ) return;

    // Prepare your order data
    $order_total = $order->get_total();
    $currency = $order->get_currency();
    $order_items = [];

    foreach ( $order->get_items() as $item ) {
        $order_items[] = [
            'name'     => $item->get_name(),
            'productId' => $item->get_product_id(),
            'price'    => $item->get_total(),
            'quantity' => $item->get_quantity()
        ];
    }

    // Convert items to valid JSON
    $items_json = wp_json_encode( $order_items );

    // Output DataLayer using Heredoc to avoid syntax conflicts
    echo <<<HTML
    <script>
    window.dataLayer = window.dataLayer || [];
    dataLayer.push({
        'event': 'purchase',
        'ecommerce': {
            'purchase': {
                'actionField': {
                    'id': '$order_id',
                    'revenue': '$order_total',
                    'currency': '$currency'
                },
                'products': $items_json
            }
        }
    });
    </script>
HTML;
}

Why This Works:

  • Heredoc (<<<HTML ... HTML;) tells PHP to treat everything in between as a plain string, so it won't misinterpret < or quotes as PHP code.
  • We use wp_json_encode() to safely convert the PHP array of order items into valid JavaScript, avoiding syntax errors in the script.

Better Approach: Follow WordPress Script Best Practices

Instead of echoing scripts directly, use WordPress's built-in script functions for cleaner, more maintainable code. This method ensures your script loads in the right place and plays nice with other plugins/themes:

add_action( 'wp_enqueue_scripts', 'enqueue_gtm_datalayer_script' );
function enqueue_gtm_datalayer_script() {
    // Only run on the WooCommerce thank you page
    if ( ! is_wc_endpoint_url( 'order-received' ) ) return;

    // Get the order ID from the page's query parameters
    $order_key = isset( $_GET['key'] ) ? sanitize_text_field( $_GET['key'] ) : '';
    $order_id = $order_key ? wc_get_order_id_by_order_key( $order_key ) : 0;
    $order = wc_get_order( $order_id );

    if ( ! $order ) return;

    // Register an empty script handle (we'll add our DataLayer code to it)
    wp_register_script( 'gtm-purchase-datalayer', '', [], false, true );

    // Build your DataLayer data array
    $datalayer_data = [
        'event' => 'purchase',
        'ecommerce' => [
            'purchase' => [
                'actionField' => [
                    'id'       => $order->get_id(),
                    'revenue'  => $order->get_total(),
                    'currency' => $order->get_currency()
                ],
                'products' => array_map( function( $item ) {
                    return [
                        'name'     => $item->get_name(),
                        'productId' => $item->get_product_id(),
                        'price'    => $item->get_total(),
                        'quantity' => $item->get_quantity()
                    ];
                }, $order->get_items() )
            ]
        ]
    ];

    // Convert data to JSON and add as inline script
    $inline_script = 'window.dataLayer = window.dataLayer || []; dataLayer.push(' . wp_json_encode( $datalayer_data ) . ');';
    wp_add_inline_script( 'gtm-purchase-datalayer', $inline_script );

    // Enqueue the script (loads in the footer by default)
    wp_enqueue_script( 'gtm-purchase-datalayer' );
}

Benefits of This Method:

  • Uses WooCommerce's is_wc_endpoint_url() to target the thank you page accurately.
  • Follows WordPress script loading standards, which helps avoid conflicts with other scripts.
  • Automatically handles JSON encoding safely, so you don't have to worry about invalid JS syntax.
  • No direct template edits—your code stays intact even when you update your theme.

Key Takeaways for Beginners

  • Never modify core or theme template files directly (like thankyou.php) unless you're using a child theme. Using hooks like woocommerce_thankyou is the official, update-safe way.
  • Always wrap HTML/JS output in PHP strings (using heredoc, nowdoc, or properly quoted strings) to avoid syntax errors.
  • Use wp_json_encode() when converting PHP data to JavaScript—it handles escaping automatically.

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

火山引擎 最新活动