Ubercart (Drupal 6) - How to filter or sort discounted (offer) products in Views module

Here is a nice little hack to filter or sort products based on discount or offer for ubercart module in drupal 6.

In drupal, ubercart module provides 3 types of price fields that can be entered for a product - Cost price, List price and Sell price. Here the sell price is the final price at which a customer can buy a product and it is a required field. To sell a product at discounted price we uses list price and sell price fields. Here the list price will be the price without discount and the sell price will be the price after discount.

By default views cannot have filtering or sorting by comparing both fields - list price and sell price. We can use the hook_view_query alter() to hack the views we created as below to do this. Before that we have to make sure to add both prices as fields in views (either as excluded or included in display) so it is available for comparing in the override function.


function hook_views_query_alter(&$view, &$query) {
// Sale products listing. To create a views listing which shows only offer products.
if($view->name == '<<view name>>' && $view->current_display == '<<view display>>') {
// Filter products with discounts only on offer page.
$query->where[0]['clauses'][] = 'uc_products.sell_price < uc_products.list_price';

// To sort products by max offers. Here when $_GET['sortby'] is passed in url it overrides the default sorting and sort product by maximum discounts.
if($view->name == '<<view name>>' && $view->current_display == '<<view display>>') {
// Check sort option for product listing
if(isset($_GET['sortby']) && $_GET['sortby'] == 'discount') {
// Sort by max discounts
$query->fields['uc_products_discounts']= array(
'field' => 'list_price - sell_price',
'table' => 'uc_products',
'alias' => 'uc_products_discounts',
$query->orderby[0] = 'uc_products_discounts DESC'; // Override default sorting.

Where to include this code? Well you need to make a custom module for this.