February 28, 2010

Showing a random product on your homepage in OpenCart

Filed under: Tips — Tags: , , — Webopius @ 4:46 pm

Another OpenCart article today (see link to the right). After this, we’ll be writing some new ASPDotNetStorefront tutorials.

Related Links…
OpenCart Open Source shopping

This tutorial will show you how to extend OpenCart and retrieve a random product from your product catalogue to display on the homepage. Each time a user refreshes the page, or a new visitor goes to your site, a different product will be shown.

First, a big thank you to the author of article on Gregg Website Development who showed a method for quickly retrieving random rows from MySQL on large datasets with minimal performance impact.

Step 1. Extend your product model with a getRandomProduct() function

The OpenCart MVC model shows it’s power here as we add a new function to the product model. Edit the ‘product.php’ file located in your site’s /catalog/model/catalog/product directory and add a new function called getRandomProduct() to the class as follows:


// Retrieve a random product from the database
public function getRandomProduct() {
   $maxminid = $this->db->query("SELECT MAX(product_id) as max_id, MIN(product_id) as min_id from ". DB_PREFIX . "product p");
   $maxrow = -1;
   $minrow = -1;
   if ($maxminid->num_rows) {
        $maxrow = $maxminid->row['max_id'];
        $minrow = $maxminid->row['min_id'];
    }
   $randomrow = mt_rand($minrow, $maxrow);
		
   $query = $this->db->query("SELECT DISTINCT *, pd.name AS name, pd.short_description as short_description, p.image, m.name AS manufacturer, ss.name AS stock FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "manufacturer m ON (p.manufacturer_id = m.manufacturer_id) LEFT JOIN " . DB_PREFIX . "stock_status ss ON (p.stock_status_id = ss.stock_status_id) WHERE p.product_id >= '" . (int)$randomrow . "' AND pd.language_id = '" . (int)$this->language->getId() . "' AND ss.language_id = '" . (int)$this->language->getId() . "' AND p.date_available <= NOW() AND p.status = '1' order by p.product_id ASC limit 1");
	
    if (!$query->row) {
        $query = $this->db->query("SELECT DISTINCT *, pd.name AS name, pd.short_description as short_description, p.image, m.name AS manufacturer, ss.name AS stock FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "manufacturer m ON (p.manufacturer_id = m.manufacturer_id) LEFT JOIN " . DB_PREFIX . "stock_status ss ON (p.stock_status_id = ss.stock_status_id) WHERE p.product_id < '" . (int)$randomrow . "' AND pd.language_id = '" . (int)$this->language->getId() . "' AND ss.language_id = '" . (int)$this->language->getId() . "' AND p.date_available <= NOW() AND p.status = '1' order by p.product_id DESC limit 1");			
    }
    return $query->row;
}

What this function does is find the maximum and minimum product ids in your database and generates a random value in this range.

It then looks for a product row with an ID >= the random ID. If none is found, it selects an ID less than the random ID. The product row is returned.

Step 2. Change your homepage controller to ask for a random product

Now, you can change any of your OpenCart controller pages to retrieve a random product. In this example, we will use the homepage controller. Find the file ‘home.php’ in your site’s /catalog/controller/common directory.

Insert the following lines into the code:


$featured = $this->model_catalog_product->getRandomProduct();
$this->data['featuredproduct'] = array(
    'name' => $featured['name'],
    'thumb'   => image_resize($featured['image'], 165, 165),
    'href' => $this->model_tool_seo_url->rewrite($this->url->http('product/product&product_id=' . $featured['product_id']))
);

This example just uses the product’s name, image thumb and URL but you can use any other available product fields returned by the SQL you created earlier. This code will create an array called $featuredproduct[] containing a single random product that can be used on your home page.

Step 3. Add the featured product to your home page

The last step involves rendering the featured product on your home page. How and where you place the product will depend very much on your site’s template and styles. The example below just shows how to display the results – you will probably want to wrap the code with css for styling.

Edit the home.tpl file with your site’s /catalog/view/theme/[your theme]/template/common directory and insert the following lines at the point you want the featured product displayed:


<b>Featured Product...</b>
<?php echo '<a class="image" href="' . $featuredproduct['href'] .'" title="' . $featuredproduct['name'] . '"><img src="'.$featuredproduct['thumb'].'" alt="' . $featuredproduct['name'].'"/></a>'; ?>
<?php echo '<b><a href="' . $featuredproduct['href'] .'" title="' . $featuredproduct['name'] . '">'. $featuredproduct['name'].'</a></b>'; ?> 

This code uses the $featuredproduct[] variable that you just created in the controller code and places a featured product thumbnail image, link and description on the home page.

More OpenCart features

This is just one example of how OpenCart can easily be extended. We have also implemented full SEO friendly URLs, news pages, product image watermarks and an updated product export/import system.

If you would like to discuss implementing an e-commerce solution based on OpenCart, please get in touch.

  • Tags