Implementing HubBox on WooCommerce

Introduction

This guide explains how to integrate the HubBox pickup point selection functionality into your WooCommerce store using the HubBox Tag script. This method involves adding HubBox's JavaScript directly into your website's frontend, typically within the checkout process.

This JavaScript injection approach is common for adding third-party features to WooCommerce checkouts.

Prerequisites:

For general information about the HubBox Tag's capabilities and core concepts, please refer to the main Tag documentation.

Step 1: Obtain Your HubBox Tag Script

First, ensure you have the correct HubBox Tag script or CDN URL from the HubBox team (e.g., your Integrations Manager). This script contains your unique HubBox configuration ID and the necessary code to display and manage the pickup point selection interface.

HubBox might provide either:

  1. A full JavaScript block to be pasted directly.
  2. A URL to a script hosted on HubBox's CDN (Content Delivery Network).

The method HubBox provides may influence which implementation option below is easier, especially regarding configuration changes later.

Step 2: Choose Your Implementation Method

There are two primary ways to add the HubBox Tag script to your WooCommerce site:

Method A: Using a Code Snippet Plugin (Recommended for Ease of Use)

Method B: Editing functions.php (Requires Child Theme)

Step 3a: Implementation via Plugin

Using a plugin simplifies adding JavaScript snippets.

Choose & Install Plugin

Select a reputable plugin designed for adding custom code snippets or header/footer scripts. Examples include:

Please note: HubBox is not affiliated with these third-party plugins. Evaluate them based on your needs, compatibility, and reviews.

Configure Snippet

Example Plugin Interface (UI varies by plugin): WP-javascript-injection

Refer to Plugin Documentation

For detailed instructions specific to your chosen plugin, consult its documentation. General WordPress guidance may also be helpful.

Step 3b: Implementation via functions.php (Child Theme / Custom Plugin)

Only use this method if you are comfortable editing PHP code and are using a Child Theme or a custom plugin. Editing your main theme's functions.php directly risks losing your changes on theme updates and can break your site if errors occur.

Access functions.php

Use the WordPress Admin interface (Appearance > Theme File Editor - select your Child Theme) or connect via FTP/SFTP to edit the functions.php file of your active Child Theme (or your custom plugin file).

Add PHP Code

Paste the appropriate PHP code snippet at the end of the file. The preferred method is using wp_enqueue_scripts:

Recommended Method: Enqueueing the Script (using CDN URL)

This method correctly adds the script to the page load queue and allows specifying footer loading. You'll need the CDN URL from HubBox.

/**
  * Enqueue HubBox Tag Script on WooCommerce Checkout Page.
  */
function enqueue_hubbox_checkout_script() {
    // Only load on the WooCommerce checkout page
    if ( function_exists( 'is_checkout' ) && is_checkout() ) {
        wp_enqueue_script(
            'hubbox-tag', // Unique handle for the script
            'YOUR_HUBBOX_CDN_SCRIPT_URL_HERE', // <-- Paste the CDN URL provided by HubBox here
            array(), // Dependencies (usually empty)
            null,    // Script version (optional)
            true     // Load script in the footer (recommended)
        );
    }
}
add_action( 'wp_enqueue_scripts', 'enqueue_hubbox_checkout_script' );

Replace YOUR_HUBBOX_CDN_SCRIPT_URL_HERE with the actual URL from HubBox. The true at the end tells WordPress to load the script in the footer.

Alternative: Embedding Full Script Block (using wp_footer)

If HubBox provided a full <script>...</script> block, you can inject it into the footer. This makes editing the script's internal config slightly easier later, but enqueueing is generally better practice.

/**
  * Add HubBox Tag Script Block to Footer on WooCommerce Checkout Page.
  */
function add_hubbox_footer_script() {
    // Only load on the WooCommerce checkout page
    if ( function_exists( 'is_checkout' ) && is_checkout() ) {
        ?>
        <script>
        // PASTE FULL HUBBOX TAG SCRIPT BLOCK HERE
        // (including the config object inside)
        // ...
        // Example structure:
        // (function() {
        //   var config = { mode: "test", /* other options */ };
        //   // ... rest of HubBox script logic ...
        // })();
        // ...
        </script>
        <?php
    }
}
add_action( 'wp_footer', 'add_hubbox_footer_script' );

Replace the comment block with the actual, complete script provided by HubBox.

Save Changes:

Save the functions.php file.

Step 4: Testing the Implementation

Enable Test Mode

Example config object:

// ... inside the HubBox Tag script OR in a preceding config definition ...
config: {
    mode: "test", // Set to "test" for testing
    // ... other configuration options ...
}
// ...

Activate Test View

What to Test

Step 5: Going Live

Once testing is complete and you are satisfied:

  1. Edit the HubBox Tag Script: Access the script via your plugin or child theme's functions.php.
  2. Change Mode: Set mode: "live" within the config object.
  3. Save Changes.

HubBox pickup options will now be live for all eligible customers.

Advanced Configuration (Within the HubBox Tag Script)

You can customize HubBox behaviour by modifying the config object within the Tag script.

Product Eligibility Filtering (getShouldBailOut)

Prevent HubBox from showing for carts with ineligible items. This uses the callbacks.getShouldBailOut function in the config, which should return true to hide HubBox. See Product Eligibility documentation for when to exclude.

To implement product eligibility filtering, add/modify the getShouldBailOut function inside config.callbacks.

WooCommerce Examples (add within config.callbacks)

Example 1: Hide pickup based on specific SKUs

Relies on product data being available in a window.dataLayer_content object, common with Google Tag Manager / GA4 setups for WooCommerce, but may not exist by default. Verify your data layer structure.

callbacks: {
  getShouldBailOut: () =>
    new Promise((resolve) => {
      try {
        const notAllowed = ["SKU-NO-PICKUP-1", "SKU-NO-PICKUP-2"]; // Your ineligible SKUs
        // Check if the assumed dataLayer path exists
        const products = window?.dataLayer_content?.ecommerce?.checkout?.products;
        if (!Array.isArray(products)) {
            console.warn("HubBox Bailout: Data layer for products not found or not an array.");
            resolve(false); // Don't bail out if data isn't there
            return;
        }
        const cartSkuList = products.map((product) => product?.sku);
        const hasNotAllowedSku = cartSkuList.some((sku) => notAllowed.includes(sku));
        resolve(hasNotAllowedSku); // Bail out (true) if found
      } catch (error) {
        console.error("HubBox Bailout SKU Check Error:", error);
        resolve(false); // Don't bail out on error
      }
    }),
}
Example 2: Hide pickup based on cart total value

Relies on scraping the total value from the DOM. This is fragile and depends heavily on your theme/checkout plugins. The specific CSS selector "#wfacp_mini_cart_start_h .order-total .woocommerce-Price-amount.amount" is likely from a specific plugin (e.g., WooFunnels) and will almost certainly need adjustment for your site. A server-side check or using WooCommerce session data via AJAX is more robust if possible.

callbacks: {
  getShouldBailOut: () => new Promise(resolve => {
    try {
      // --- Selector MAY NEED CHANGING for your theme ---
      var selector = ".shop_table.woocommerce-checkout-review-order-table .order-total .woocommerce-Price-amount.amount"; // Example standard WC selector
      var totalElement = document.querySelector(selector);
      if (!totalElement) {
          console.warn("HubBox Bailout: Cart total element not found with selector:", selector);
          resolve(false); // Don't bail out if element not found
          return;
      }
      // Attempt to parse currency - adjust based on your store's format
      var total = Number(totalElement.innerText.replace(/[^0-9.,]+/g, "").replace(",",".")); // Handle symbols & decimal separators
      const maxPickupValue = 5000; // Set your threshold
      resolve(total >= maxPickupValue); // Bail out (true) if total meets or exceeds threshold
    } catch(error) {
      console.error("HubBox Bailout Value Check Error:", error);
      resolve(false); // Don't bail out on error
    }
  }),
}

Shipping Rate Filtering

You can use configuration within the HubBox Tag to target and hide shipping rate HTML elements. This behavior is configured via config.shippingMethods. See Shipping Rate Filtering documentation for strategy.

Example Configuration (Conceptual - using shippingMethods structure from original example)
// ... inside the HubBox Tag script config ...
config: {
    shippingMethods: {
        wrapper: '#shipping_method',
            interactionPreventionAction: 'hide li',
                excludeOnLocalPickup: [
                    {
                        selectors: [
                            'text-fragment: Royal Mail',
                            'text-fragment: Evri',
                        ],
                    },
                ],
            },
}

The End Result

Once correctly implemented and live, customers on your WooCommerce checkout page will see the HubBox pickup option. They can search for and select a location, and upon selection, their WooCommerce shipping address will update to the chosen pickup point address before they complete payment.

Support

If you face issues during WooCommerce setup or testing, please provide details (screenshots, console errors, theme/plugin info) to the HubBox Client Support team at clientsupport@hub-box.com.