If you haven’t gone through the first part of this series, I would recommend you do so as that’s something essential to go through before you develop the files in this article.
As a quick reminder, we’re developing a Recent Products plugin that lists X number of products in the front-end. You can configure the number of products to be displayed from the back-end configuration form that was built in part one of this series. We also went through the plugin architecture of OpenCart, and it’ll be applied to the front-end plugin development as well.
As mentioned earlier, in the course of this tutorial we’ll develop front-end plugin files, so let’s have a quick look at the list of files that need to be implemented.
catalog/language/english/module/recent_products.php
: It's a file that holds static labels used throughout the front-end application area.catalog/controller/module/recent_products.php
: It's a controller file that holds the application logic of our module.catalog/model/module/recent_products.php
: It’s a model file that is used to interact with the database to fetch products.catalog/view/theme/default/template/module/recent_products.tpl
: It's a view template file and holds XHTML code.The obvious difference you'll have noticed here is that it’s the catalog directory that holds the front-end plugin files as opposed to the admin directory that was used to create the back-end plugin files. Also, there’s a model file, which was not created for the back-end, that holds the business logic of our plugin to fetch recent products from the database.
The other important thing to note is the placement of the view template file recent_products.tpl
. Generally in the front-end, you would have more than one theme to deal with, and that’s handled with an additional theme directory. It’s the default theme directory of OpenCart that provides most of the template files.
Apart from this, it’s a very similar plugin structure that also contains language and controller files.
To start with, let’s create a language file catalog/language/english/module/recent_products.php
with the following contents.
<?php // catalog/language/english/module/recent_products.php // Heading $_['heading_title'] = 'Recent Products';
It’s used to set up static labels that will be used in a view template file. It’s almost identical to that of the admin language file.
Next, we’ll create a controller file that should placed at catalog/controller/module/recent_products.php
.
<?php // catalog/controller/module/recent_products.php class ControllerModuleRecentProducts extends Controller { public function index($setting) { $this->load->language('module/recent_products'); $data['heading_title'] = $this->language->get('heading_title'); $this->load->model('module/recent_products'); $this->load->model('tool/image'); $data['products'] = array(); $results = $this->model_module_recent_products->getRecentProducts($setting['limit']); if ($results) { foreach ($results as $result) { if ($result['image']) { $image = $this->model_tool_image->resize($result['image'], 100, 100); } else { $image = $this->model_tool_image->resize('placeholder.png', 100, 100); } if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) { $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax'))); } else { $price = false; } if ((float)$result['special']) { $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax'))); } else { $special = false; } $data['products'][] = array( 'product_id' => $result['product_id'], 'thumb' => $image, 'name' => $result['name'], 'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get('config_product_description_length')) . '..', 'price' => $price, 'special' => $special, 'href' => $this->url->link('product/product', 'product_id=' . $result['product_id']) ); } if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/recent_products.tpl')) { return $this->load->view($this->config->get('config_template') . '/template/module/recent_products.tpl', $data); } else { return $this->load->view('default/template/module/recent_products.tpl', $data); } } } }
Again, the index
method is the place where most of our code should go in. As with most of the other plugins, you’ll find an argument $setting
is available in the index method. Recall the admin configuration form developed in part one that was used to configure plugin parameters—that is what the $setting
variable stands for. It holds plugin configuration values in the form of an array.
The $this->load->language
shorthand loads the front-end plugin language file, and we've already it discussed in depth in the first part. Similarly, the $this->load->model
shorthand loads the plugin model file created at catalog/model/module/recent_products.php
. We’re also loading the Image
model defined under the tool
directory as it contains utility methods to resize images.
The most important call in the index method is the call to the getRecentProducts
method that provides an array of recent products from the database. Of course, we’ll see it in detail during the discussion of the model file. As an argument of the method, the $setting['limit']
value configured in the back-end configuration form is passed.
$results = $this->model_module_recent_products->getRecentProducts($setting['limit']);
Next, we iterate through an array of products and prepare the $data['products']
array that will be used in the view template file. In the process, we use the resize method of the Image model class to create thumbnail images, as it won’t make any sense to display original product images in the front-end.
You’ll also find $this->config->get
kind of snippets that are used to fetch global store configuration values. You could configure your store settings under System > Settings.
Also, the $this->url->link
shorthand is used to create SEO-friendly product page links. Finally, there’s a snippet to load the template file recent_products.tpl
that prepares the actual output using the $data
array.
As opposed to the back-end, you’ll see conditional loading of the view template file as shown below. The reason is that you could have configured a different theme, other than the default theme, for your front-end. If there’s no other theme configured, it’s a default theme that is always used as a fallback.
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/recent_products.tpl')) { return $this->load->view($this->config->get('config_template') . '/template/module/recent_products.tpl', $data); } else { return $this->load->view('default/template/module/recent_products.tpl', $data); }
So, that’s the end of the controller file. Let’s go ahead and create a model file at catalog/model/module/recent_products.php
.
<?php // catalog/model/module/recent_products.php class ModelModuleRecentProducts extends Model { public function getRecentProducts($limit) { $this->load->model('catalog/product'); $product_data = $this->cache->get('product.recent.' . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' . $this->config->get('config_customer_group_id') . '.' . (int)$limit); if (!$product_data) { $query = $this->db->query("SELECT p.product_id FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "' ORDER BY p.date_added DESC LIMIT " . (int)$limit); foreach ($query->rows as $result) { $product_data[$result['product_id']] = $this->model_catalog_product->getProduct($result['product_id']); } $this->cache->set('product.recent.' . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' . $this->config->get('config_customer_group_id') . '.' . (int)$limit, $product_data); } return $product_data; } }
As per the conventions, the model class name starts with the Model
keyword and follows the directory structure. It also extends the base Model
class that provides utility objects and methods to interact with the database.
We’re also loading the Product
model defined under the catalog
directory using $this->load->model('catalog/product')
syntax, since we’ll need to use methods defined in that class.
A couple of other handy shorthands are $this->cache->set
and $this->cache->get
. The first one is used to set the value in the cache, and the latter one gets the already stored cache value by key. It’s a good habit to use caching appropriately to improve the overall performance of your store.
Finally, we’re executing a database query to fetch recent products, and the $this->db->query
syntax helps us to do that. It’s a shorthand that runs the query method of the database class.
Next, we iterate through all the product records and load product information by calling the getProduct
method of the Product
model class. At the end, we save the array information to the cache so that in the subsequent requests we don’t have to do all the heavy lifting again!
Finally, there’s only the view file recent_products.tpl
that needs to be created to complete our custom plugin. Let’s do that by creating it at catalog/view/theme/default/template/module/recent_products.tpl
.
<!-- catalog/view/theme/default/template/module/recent_products.tpl --> <h3><?php echo $heading_title; ?></h3> <div class="row"> <?php foreach ($products as $product) { ?> <div class="product-layout col-lg-3 col-md-3 col-sm-6 col-xs-12"> <div class="product-thumb transition"> <div class="image"><a href="<?php echo $product['href']; ?>"><img src="<?php echo $product['thumb']; ?>" alt="<?php echo $product['name']; ?>" title="<?php echo $product['name']; ?>" class="img-responsive" /></a></div> <div class="caption"> <h4><a href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?></a></h4> <p><?php echo $product['description']; ?></p> <?php if ($product['price']) { ?> <p class="price"> <?php if (!$product['special']) { ?> <?php echo $product['price']; ?> <?php } else { ?> <span class="price-new"><?php echo $product['special']; ?></span> <span class="price-old"><?php echo $product['price']; ?></span> <?php } ?> </p> <?php } ?> </div> </div> </div> <?php } ?> </div>
In the view file, we’re just iterating through the $products
array supplied by the controller to produce the product listing XHTML.
So, that’s the end of our front-end plugin files! In the next section, I’ll show you how to assign our plugin to the OpenCart layout so that it can be displayed on the front-end.
For any plugin to be displayed on the front-end, we need to assign it to one of the available layouts. For example purposes, we’ll go ahead and assign our plugin to the Content Top position.
Head over to the back-end and navigate to System > Design > Layouts. That should list all the available layouts in your store. Edit the Home layout, and it brings you the layout editing screen. You just need to add a new module entry as shown in the following screenshot.
As you can see, we’ve picked up the Recent Products > My Recent Block Plugin and assigned it to the Content Top position. Save the settings and you’re good to go!
Go ahead to the front-end and you should be able to see a pretty decent-looking Recent Products block, as shown in the following screenshot.
So, that ends the journey of our custom plugin development series in OpenCart. Although the series was aimed at beginners, it should also provide a nice custom plugin template that could be extended as per your requirements.
I encourage you to explore it on your own and add more functionalities. That should be a decent exercise after leaving this tutorial!
In this series, we’ve discussed custom plugin development in OpenCart. As it was targeted for beginners, we ended up developing a very simple custom plugin that lists recent products in a block in the front-end. Earlier, in the first part, we also created a back-end configuration form for our plugin.
For additional OpenCart tools, utilities, extensions, and so on that you can leverage in your own projects or for your own education, don't forget to see what we have available in the marketplace.
Don’t hesitate to leave your feedback and queries using the comment feed below!
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/WordPress Website Maintenance Guide For Beginners
/How Long Does It Take to Learn JavaScript?
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Getting Started With Django: Newly Updated Course
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
/Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: HTTP
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Learn Computer Science With JavaScript: Part 1, The Basics
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
/Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20Creating a Blogging App Using React, Part 1: User Sign-In
/9 More Popular HTML5 Projects for You to Use and Study
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
/New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…