• Resolved jfcypher

    (@taojing10)


    Hi, we have a special page need include trakcer.js, I realize this file is not in wp-footer, instead, it is in wp-header. Is there any setting made this change?

    Anyway mannually add tracker.js by php code or functions.php?

Viewing 6 replies - 1 through 6 (of 6 total)
  • Plugin Support Mehmet

    (@gandomi)


    Hi @taojing10,
    Thanks for your message. The tracker.js file alone is not enough to enable tracking. This file relies on a configuration object that is passed from PHP to JavaScript using wp_localize_script. Without this object, the tracker cannot initialize properly.
    For example, to add the tracker to a specific page, you can use the following approach in your functions.php:

    <?php
    // Hook into wp_enqueue_scripts
    add_action('wp_enqueue_scripts', 'my_enqueue_tracker_js', 11);

    function my_enqueue_tracker_js() {
    // Define your data to pass to JavaScript
    $tracker_data = array(
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'siteUrl' => site_url(),
    'option' => array(
    'dntEnabled' => false,
    'bypassAdBlockers' => false,
    'isPreview' => is_preview(),
    // Add your custom options here
    'customOption' => 'your_value',
    ),
    'customParams' => array(
    // Your custom parameters
    'key1' => 'value1',
    'key2' => 'value2',
    ),
    );

    // Dependencies (if tracker.js depends on other scripts)
    $dependencies = array('jquery'); // Add any dependencies here

    // Enqueue the script
    wp_enqueue_script(
    'my-tracker-js', // Handle
    plugin_dir_url(__FILE__) . 'js/tracker.js', // Path to your tracker.js
    $dependencies, // Dependencies
    '1.0.0', // Version
    true // Load in footer
    );

    // Localize script - passes data to JavaScript
    wp_localize_script(
    'my-tracker-js', // Same handle as above
    'MyTrackerObject', // JavaScript object name
    $tracker_data // The data array
    );
    }

    This ensures both the JS file and its configuration are properly loaded for that page.
    For more details and a working example, you can check this link: WP Statistics FluentCommunity Tracking Example
    Best regards,

    Thread Starter jfcypher

    (@taojing10)

    Thanks Mehmet, try to understand this code better, how/where to tell this function will apply to specific page? For example if I want to apply it to /example_page, and this page isnt include wp-foot and wp-head, how can I use your code?

    Plugin Support Mehmet

    (@gandomi)

    Hi @taojing10,

    Thanks for the follow-up questions.

    There are two separate points here, and it’s important to keep them distinct.

    First, why tracker.js is loading in the header.

    This behavior is always controlled by code.

    There is no WordPress setting that globally moves scripts from the footer to the header.

    This usually happens if the script was enqueued with $in_footer = false,

    or if another script depends on it and must load in the header,

    or if the theme or template does not call wp_footer().

    Second, how to load tracker.js only on a specific page.

    If the page is a normal WordPress page and includes wp_head() and wp_footer(),

    you can safely use conditionals inside wp_enqueue_scripts.

    Example: load only on a page by slug.

    add_action( 'wp_enqueue_scripts', 'my_enqueue_tracker_js', 11 );
    
    function my_enqueue_tracker_js() {
    
        if ( ! is_page( 'example_page' ) ) {
            return;
        }
    
        wp_enqueue_script(
            'my-tracker-js',
            plugin_dir_url( __FILE__ ) . 'js/tracker.js',
            array(),
            '1.0.0',
            true
        );
    
        wp_localize_script(
            'my-tracker-js',
            'MyTrackerObject',
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'siteUrl' => site_url(),
            )
        );
    }

    You can also target pages in other ways.

    is_page( 123 );                    // Page ID
    is_page( 'example-page' );         // Page slug
    is_page_template( 'custom.php' );  // Page template
    is_singular( 'post' );             // Post type

    The critical issue in your case.

    If the page does not include wp_head() and wp_footer(),

    WordPress cannot inject scripts at all.

    This means wp_enqueue_script, wp_localize_script,

    and most plugins (including WP Statistics) will not work.

    Best solution: fix the template.

    Add these hooks to the page template.

    <head>
        <?php wp_head(); ?>
    </head>
    
    <body>
        ...
        <?php wp_footer(); ?>
    </body>

    This immediately restores compatibility with tracking and other plugins.

    Last resort: manual output.

    If the page is truly standalone and cannot use WP hooks,

    you must manually output both the script and its configuration.

    <script src="/path/to/tracker.js"></script>
    <script>
    var MyTrackerObject = {
    ajaxUrl: "&lt;?php echo admin_url('admin-ajax.php'); ?&gt;",
    siteUrl: "&lt;?php echo site_url(); ?&gt;",
    option: {
    dntEnabled: false,
    bypassAdBlockers: false,
    isPreview: false
    },
    hitParams: {}
    };
    </script>

    This approach bypasses WordPress and is harder to maintain.

    If you’d like, you can share how /example_page is built

    (page template, custom PHP file, or plugin output),

    and I can tell you exactly where the fix should go.

    Best regards,

    Thread Starter jfcypher

    (@taojing10)

    Hi, I use manual output option, give me js error: Uncaught ReferenceError: WP_Statistics_Tracker_Object is not defined

    anything missing?

    Plugin Support Mehmet

    (@gandomi)

    Hi @taojing10,

    Sorry for the inconvenience caused.

    This error happens because the WP_Statistics_Tracker_Object variable is not defined before loading tracker.js.

    When using the Manual Output option, you need to manually print this variable.

    Please add the following code after the </body> tag in your theme template (or any template that outputs the page):

    <?php
    // Manual WP Statistics Tracker
    if (defined('WP_STATISTICS_VERSION') && \WP_STATISTICS\Option::get('use_cache_plugin')) {
    // Get page type info
    $get_page_type = \WP_STATISTICS\Pages::get_page_type();

    // Build hit params
    $params = [
    'wp_statistics_hit' => 1,
    'source_type' => $get_page_type['type'],
    'source_id' => $get_page_type['id'],
    'search_query' => isset($get_page_type['search_query']) ? base64_encode(esc_html($get_page_type['search_query'])) : '',
    ];

    // Add signature if enabled
    if (\WP_STATISTICS\Helper::isRequestSignatureEnabled()) {
    $params['signature'] = \WP_Statistics\Utils\Signature::generate([
    $get_page_type['type'],
    (int)$get_page_type['id']
    ]);
    }

    // Build request URL based on bypass_ad_blockers setting
    if (\WP_STATISTICS\Option::get('bypass_ad_blockers', false)) {
    $requestUrl = get_site_url();
    $hitParams = array_merge($params, ['action' => 'wp_statistics_hit_record']);
    } else {
    $requestUrl = get_rest_url(null, 'wp-statistics/v2');
    $hitParams = array_merge($params, ['endpoint' => 'hit']);
    }

    // Build JS args
    $jsArgs = [
    'requestUrl' => $requestUrl,
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'hitParams' => $hitParams,
    'option' => [
    'dntEnabled' => \WP_STATISTICS\Option::get('do_not_track'),
    'bypassAdBlockers' => \WP_STATISTICS\Option::get('bypass_ad_blockers', false),
    'consentIntegration' => \WP_Statistics\Service\Integrations\IntegrationHelper::getIntegrationStatus(),
    'isPreview' => is_preview(),
    'userOnline' => false,
    'trackAnonymously' => \WP_Statistics\Service\Integrations\IntegrationHelper::shouldTrackAnonymously(),
    'isWpConsentApiActive' => \WP_Statistics\Service\Integrations\IntegrationHelper::isIntegrationActive('wp_consent_api'),
    'consentLevel' => \WP_STATISTICS\Option::get('consent_level_integration', 'functional'),
    ],
    'onlineParams' => array_merge($params, ['action' => 'wp_statistics_online_check']),
    'jsCheckTime' => 60000,
    ];
    ?>
    <script>
    var WP_Statistics_Tracker_Object = <?php echo wp_json_encode($jsArgs); ?>;
    </script>
    <script src="<?php echo esc_url(WP_STATISTICS_URL . 'assets/js/tracker.js?ver=' . WP_STATISTICS_VERSION); ?>"></script>
    <?php
    }
    ?>

    I just tested this setup in a theme template, and it works correctly.

    Please try it on your side and let me know the result.

    Kind regards,
    Mehmet

    Plugin Support Mehmet

    (@gandomi)

    Hi @taojing10,

    Since we haven’t heard back from you, we’ll go ahead and mark this topic as resolved for now.

    If you still need assistance, feel free to reopen this topic or create a new one and we’ll be happy to
    help.

    Best regards

Viewing 6 replies - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.