Customised Product Prices

The Default for WebTemplate is to use the "Price" attribute of a product to calculate its price.

Instead, a custom method may be defined to calculate a product's price by extending the WTProduct class, overriding the getPrice function and regsitering the class to the Product Node Type

Example, using a different price if the customer has ordered more than 12 of a product

<?php
class Product extends WTProduct {
  // quantity is the quantity to calcuate the price for
  // quantityOrdered is the quantity of the product which has been added to the cart
  public function getPrice($quantity = 1, $quantityOrdered = 1, $args = Array()) {
    $priceEach = $this->getAttribute("Price");
    if($quantityOrdered > 12) {
      $priceEach = $this->getAttribute("Price for 12");
      if($priceEach == 0) {
        $priceEach = $this->getAttribute("Price");
      }
    }
    return $priceEach * $quantity;
  }
}

// register the class to the node type
$GLOBALS["WT"]->registerNodeTypeClass("Product", "Product");
?>

Example: Use a product's 'Member Price' attribute for the price if it is non-zero and a member is logged in:

<?php

class Product extends WTProduct {
  public function getPrice($quantity = 1, $quantityOrdered = 1, $args = Array()) {
    $currentUser = $GLOBALS["WT"]->getCurrentUser();
    if($currentUser->isMember()) {
      $memberPrice = $this->getAttribute("Member Price");
      if($memberPrice > 0) {
        return $memberPrice * $quantity;
      }
    }
    return parent::getPrice($quantity, $quantityOrdered, $args);
  }
}

$GLOBALS["WT"]->registerNodeTypeClass("Product", "Product");

?>

The $args parameter can be used to pass extra information about the product. eg the cart will pass all information stored about the product in the cart to the getPrice function through the $args parameter.

eg:

Add a product to the cart through PHP:

<?php

  // add product to cart
  $cart = new WTCart();
  $cart->set($cartKey, Array("productGuid" => $productGuid, "quantity" => $quantity, "description" => "test product", "product type" => "multi"));

?>

 

// products of type multi will use the "Multi Price" for their price

<?php

class Product extends WTProduct {
  public function getPrice($quantity = 1, $quantityOrdered = 1, $args = Array()) {
    if(array_key_exists("product type", $args) && $args["product type"] == "multi") {
      return $this->getAttribute("Multi Price");
    }    
    return parent::getPrice($quantity, $quantityOrdered, $args);
  }
}

$GLOBALS["WT"]->registerNodeTypeClass("Product", "Product");

?>