You are here

function _uc_googleanalytics_ecommerce_script in Ubercart 5

1 call to _uc_googleanalytics_ecommerce_script()
uc_googleanalytics_footer in uc_googleanalytics/uc_googleanalytics.module
Implementation of hook_footer().

File

uc_googleanalytics/uc_googleanalytics.module, line 147
Adds the required HTML and Javascript to the checkout complete page to allow e-commerce statistics tracking through Google Analytics.

Code

function _uc_googleanalytics_ecommerce_script($order) {
  $script = '';
  $transaction = '';
  $items = '';
  $tax = 0;
  $shipping_cost = 0;

  // Finding name of country, if not use the country code from ubercart
  if ($country_data = uc_get_country_data(array(
    'country_id' => $order->billing_country,
  ))) {
    $country = $country_data[0]['country_name'];
  }
  else {
    $country = $order->billing_country;
  }
  foreach ($order->products as $product) {
    $category = '';

    // Try to find a category (term) for the product. Since products most often
    // only have one category, the first one returned (based on tid) is chosen.
    if (module_exists('taxonomy')) {
      $terms = taxonomy_node_get_terms($product->nid);
      if (count($terms)) {
        $term = array_shift($terms);
        $category = $term->name;
      }
    }
    if (empty($category)) {
      $category = t('No category');
    }

    // using the model field as SKU
    $items .= 'pageTracker._addItem("' . $order->order_id . '", ' . drupal_to_js($product->model) . ', ' . drupal_to_js($product->title) . ', ' . drupal_to_js($category) . ', "' . $product->price . '", "' . $product->qty . '");';
  }
  foreach ($order->line_items as $line_item) {
    if ($line_item['type'] == 'tax') {
      $tax += $line_item['amount'];
    }
    if ($line_item['type'] == 'shipping') {
      $shipping_cost += $line_item['amount'];
    }
  }
  $transaction = 'pageTracker._addTrans("' . $order->order_id . '", ' . drupal_to_js(variable_get('uc_store_name', 'Ubercart')) . ', "' . $order->order_total . '", "' . $tax . '", "' . $shipping_cost . '", ' . drupal_to_js($order->billing_city) . ', ' . drupal_to_js($order->billing_postal_code) . ', ' . drupal_to_js($country) . ');';
  $script .= $transaction;
  $script .= $items;
  $script .= 'pageTracker._trackTrans();';
  uc_add_js($script, 'inline', 'footer');
}