Admin Catalog Product listing default sort order to latest inserted product

OpenCart Product listing default sort order is as per product name, and you can sort them with product name ASC or DESC, Model ASC or DESC, price ASC or DESC, quantity ASC or DESC and Status ASC or DESC just by clicking on the listing of the table heading.

Opencart Product listing by product_id

But if you want to sort as per the latest inserted product then you need to do some code changes in default file which is not good but requirements always come first. (OcMod coming soon)

Find the following lines of code in admin\controller\catalog\product.php:

if (isset($this->request->get['sort'])) {
    $sort = $this->request->get['sort'];
} else {
    $sort = 'pd.name';
}

if (isset($this->request->get['order'])) {
    $order = $this->request->get['order'];
} else {
    $order = 'ASC';
}

Replace with the following lines of code:

if (isset($this->request->get['sort'])) {
    $sort = $this->request->get['sort'];
} else {
    $sort = 'pd.product_id';
}

if (isset($this->request->get['order'])) {
    $order = $this->request->get['order'];
} else {
    $order = 'DESC';
}

With this, the product listing will be listed with the latest product inserted by default, and click on table titles as per your req

Twig Template coming in OpenCart 2.3

In the upcoming OpenCart 2.3, both template engines will be supported PHP template and twig engine.

OpenCart will allow you to override all of the templates that are used to produce HTML markup so that you can fully control the markup that is being outputted within a custom theme. There are templates for each page element ranging from the high-level HTML to small fields.

twig template opencart

What is Twig?

Twig is a modern template engine for PHP

  • Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.
  • Secure: Twig has a sandbox mode to evaluate the untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.
  • Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.

You can find the Twig website at https://twig.symfony.com/
Documentation: https://twig.symfony.com/doc/3.x/

You can update your preexisting OpenCart theme by replacing PHP codes to twig codes and changing .tpl template file extension to .twig extension.

  • .tpl will use the PHP engine
  • .twig will use the Twig engine

Below is one example of regular expression code to help with your PHP IDE to mass search and replace basic PHP syntax with Twig syntax.

<?php echo $var; ?>

<\?php echo [$](\w*\b)[;] \?\>

{{ $1 }}

<?php echo $error_name[$language['language_id']]; ?>

<\?php\s+echo\s+[$](\w+)\[[$](.*)\[\'(.*)\'\]\]\; \?\>

{{ $1[$2.$3] }}

All details are provided at https://github.com/opencart/opencart/wiki/Upgrading-themes-from-2.3-to-2.3

Now in template section you can write following :

To show header section: {{ header }}

To show bottom content: {{ content_bottom }}

Similarly, {{ content_top }}, {{ column_right }}, {{ column_left }}, {{ footer }}

Previously breadcrumb codes at .tpl files used to look like below:

<ul class="breadcrumb">
    <?php foreach ($breadcrumbs as $breadcrumb) { ?>
    <li><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a></li>
    <?php } ?>
  </ul>

But now with .twig it looks like below:

 <ul class="breadcrumb">
    {% for breadcrumb in breadcrumbs %}
    <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
    {% endfor %}
  </ul>

Thus, it seems twig consist features like: concise, template oriented syntax, full featured, easy to learn, extensibility, unit tested, documented, secure, clean error messages and fast which I believe will improve development speed.

Thanks for the OpenCart team on using Twig.

Feedback or Testimonials Module for Opencart 2.2 for Free

Feedback or Testimonial Module is the module for Opencart by which customers can provide their feedback about the site or product or any services. We were encouraged to develop it because there is a review system for the products but not for the site and services so we made this feedback or testimonial module.

INSTALLATION OF FILES:

  1. Unzip the zip file where you will find “Testimonial-OpenCart-Module-Free-master” folder.
  2. “Testimonial-OpenCart-Module-Free-master” folder contains “admin” and “catalog” folder
  3. Upload the files and folders of the admin and catalog folder to your OpenCart root folder. You can use FTP or SFTP to upload these files and folders.
  4. After completing uploading, login to the admin section, go to Extensions > Modules.
  5. Go to “Testimonial” and click the green install button.
    install_opencart_module_webocreation
  6. Our Testimonial module is installed. Now click blue edit button. If this is first time then you will see like the following image to install the database.
    database-not-found
  7. Click the Install Database button and three tables are created in database. As following sql queries are run, for easy installation I created this way.

    CREATE TABLE oc_testimonial ( testimonial_id int(11) NOT NULL, name varchar(64) NOT NULL, status tinyint(1) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE oc_testimonial_image ( testimonial_image_id int(11) NOT NULL, testimonial_id int(11) NOT NULL, link varchar(255) NOT NULL, image varchar(255) NOT NULL, sort_order int(3) NOT NULL DEFAULT '0' ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE oc_testimonial_image_description ( testimonial_image_id int(11) NOT NULL, language_id int(11) NOT NULL, testimonial_id int(11) NOT NULL, title varchar(64) NOT NULL, message text NOT NULL, name varchar(250) NOT NULL, position varchar(250) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ALTER TABLE oc_testimonial ADD PRIMARY KEY (testimonial_id); ALTER TABLE oc_testimonial_image ADD PRIMARY KEY (testimonial_image_id); ALTER TABLE oc_testimonial_image_description ADD PRIMARY KEY (testimonial_image_id,language_id); ALTER TABLE oc_testimonial MODIFY testimonial_id int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; ALTER TABLE oc_testimonial_image MODIFY testimonial_image_id int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=144;
  8. Wait did you see Permission Denied message. Then it means you do not have permission to access this page, please refer to your system administrator. If you are administrator then Go to the System >> Users >> User Groups and edit the “Administrator” or related user group  and then check checkbox “module/testimonial” and “design/testimonial” in both Access Permission and Modify Permission as in the figure. For easiness you can click “Select All” in both permission and grant all access ( Do this only for top administrator).
    user-group-grant-permission
  9. Once you grant permission, you will be able install the database and install the module. Now edit the “Testimonial” module and click the “Install Database” blue button.
  10. Now you will see as following image where you will insert the Testimonial, click the Insert Testimonial button.
    insert-testimonial
  11. You can insert multiple list of testimonial so you can show different testimonials in different layouts.
    insert-testimonials
  12. Now start to inserting testimonials by clicking the blue button and see the image what goes where:
    testimonial-insertion-form
  13. After inserting these you choose that into the testimonial module. Go to Admin>> Extensions>> Modules >> Testimonial >> Edit
  14. Now activate Testimonial module
    activate-module-testimonial
  15. Now go to Admin >> Design >> Layout, then edit the “Category” from the list. We are showing our testimonial module at category left column.
    activate-layout-section
  16. Now view any category page and you will see like the image below:
    front-end
  17. presentation-layer
  18. You are ready to go live.
  19. If you feel like you have to change the CSS then you can edit catalog/view/theme/default/module/testimonial.tpl. We integrate the CSS in the same file so that it does not conflict with others.
  20. If you want to change animation then you can set at catalog/view/theme/default/module/testimonial.tpl

<script type="text/javascript">
    $('#testimonial<?php echo $module; ?>').owlCarousel({ 
        items: 6, 
        autoPlay: 5000, 
        singleItem: true, 
        navigation: false, 
        pagination: false,     
        rtl:true, 
        transitionStyle: 'fade' 
    });
</script>

Other than that if you need help then please comment below.

Thanks
Rupak Nepali

COPYRIGHT:

This module code is the intellectual property of the designers involved in its creation. As an Opensource code you are entitled to use it freely and modify it if you wish but please keep the credits intact.

Enjoy!

How to pull products JSON through API in Opencart?

In this tutorial, we show how to pull products in JSON format through API in Opencart. First, read the post below to understand the OpenCart API:

We take an example between two servers one from https://webocreation.com/nepalbuddha which acts as Server Responder of API which is built in OpenCart and https://tuliprsdynasty.com/api/ as the requestor.

Opencart API explained

Responding server

OpenCart does not provide API to show the products by default so we need to make some changes in responding server to show all products. For that in your responding server go to catalog/controller/api/ and create product.php and paste following lines of code:

<?php
class ControllerApiProduct extends Controller
{
    public function index()
    {
        $this->load->language('api/cart');
        $this->load->model('catalog/product');
        $this->load->model('tool/image');
        $json = array();
        $json['products'] = array();
        $filter_data = array();
        $results = $this->model_catalog_product->getProducts($filter_data);
        foreach ($results as $result) {
            if ($result['image']) {
                $image = $this->model_tool_image->resize($result['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height'));
            } else {
                $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height'));
            }
            if ($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')), $this->session->data['currency']);
            } 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')), $this->session->data['currency']);
            } else {
                $special = false;
            }
            if ($this->config->get('config_tax')) {
                $tax = $this->currency->format((float) $result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']);
            } else {
                $tax = false;
            }
            if ($this->config->get('config_review_status')) {
                $rating = (int) $result['rating'];
            } else {
                $rating = false;
            }
            $data['products'][] = array(
                'product_id' => $result['product_id'],
                'thumb' => $image,
                'name' => $result['name'],
                'description' => utf8_substr(trim(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'))), 0, $this->config->get('theme_' . $this->config->get('config_theme') . '_product_description_length')) . '..',
                'price' => $price,
                'special' => $special,
                'tax' => $tax,
                'minimum' => $result['minimum'] > 0 ? $result['minimum'] : 1,
                'rating' => $result['rating'],
                'href' => $this->url->link('product/product', 'product_id=' . $result['product_id']),
            );
        }
        $json['products'] = $data['products'];
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

With the above code it will provide you directly accessing API URL index.php?route=api/product. As per our example, it is https://webocreation.com/nepalbuddha/index.php?route=api/product. Here we did not do any authentication and authorization. It directly shows all products whoever is called from that URL. In our upcoming post, we will show how to show categories to API users only.

Requesting server

In your requesting server, create a file lets say apiproducts.php, as per our example let’s say we create https://tuliprsdynasty.com/api/apiproducts.php In this file let’s make a CURL request to the get the products: https://webocreation.com/nepalbuddha/index.php?route=api/product. Following is the code:

<?php
$url = "https://webocreation.com/nepalbuddha";
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $url . "/index.php?route=api%2Fproduct",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

Finally, the response you get will be like below:

{
    "products": [{
        "product_id": "30",
        "thumb": "https:\/\/webocreation.com\/nepalbuddha\/image\/cache\/catalog\/demo\/canon_eos_5d_1-228x228.jpg",
        "name": "Canon EOS 5D",
        "description": "Canon's press material for the EOS 5D states that it 'defines (a) new D-SLR category', while we're n..",
        "price": "$122.00",
        "special": "$98.00",
        "tax": "$80.00",
        "minimum": "1",
        "rating": 0,
        "href": "https:\/\/webocreation.com\/nepalbuddha\/index.php?route=product\/product&product_id=30"
    }, {
        "product_id": "47",
        "thumb": "https:\/\/webocreation.com\/nepalbuddha\/image\/cache\/catalog\/demo\/hp_1-228x228.jpg",
        "name": "HP LP3065",
        "description": "Stop your co-workers in their tracks with the stunning new 30-inch diagonal HP LP3065 Flat Panel Mon..",
        "price": "$122.00",
        "special": false,
        "tax": "$100.00",
        "minimum": "1",
        "rating": 0,
        "href": "https:\/\/webocreation.com\/nepalbuddha\/index.php?route=product\/product&product_id=47"
    }]
}

As per our API set up, it just returns product_id, thumb, name, description, price, special, tax, minimum, rating, and link of the product. If you want to make changes then you have to make changes in catalog/controller/api/product.php as per your need. In this way, you can retrieve all products in JSON format through API.

You can check following Opencart API related posts:

Please don’t forget to post your questions or comments so that we can add extra topics. Likewise, you can follow us at our twitter account @rupaknpl and subscribe to our YouTube channel for Opencart tutorials.

OpenCart API documentation to create, read, query, update, and upsert

The OpenCart API allows your application to access current data within OpenCart through the API, several common operations can be performed. Operations include:

  • create — Creates with the specified parameters.
    For example, you can add products to the cart as given by OpenCart API post request of products or product_id at
    /index.php?route=api/cart/add
  • read — Retrieves information about the specified object.
    For example, you can retrieve the shipping methods with the endpoint: index.php?route=api/shipping/methods
  • query — Retrieves objects that match specified criteria.
  • update — Updates elements of an existing object.
  • upsert — Updates elements of an existing object if it exists. If the object does not exist, one is created using the supplied parameters.

Developers must authenticate with the API before issuing requests.

Some considerations must be taken while performing requests. When performing update requests, only the fields specified in the request are updated, and all others are left unchanged. If a required field is cleared during an update, the request will be declined.

Request Format

All requests:

  • Must use either HTTP GET or POST
  • Must pass credentials in an HTTP Authorization header – or – in the body of a POST request

Authentication and Request Format of OpenCart API:

Authentication requests sent to the OpenCart API URL:

  1. it must be made via SSL encrypted connection
  2. Must use HTTP POST
  3. Must contain usernameand key for the Opencart user account that will be submitting API requests

Login requests that meet these criteria will be granted an api_token id.

You can see the API username and API key at Admin >> System >> Users >> API

Both UserNAME and API key are unique to individual users. API Token ID is valid for 60 minutes. In contrast, user keys are valid indefinitely which you can regenerate as needed.

Request Parameters

ParameterRequiredDescription
usernameXThe API username
keyXThe API keys generated for the API user

CURL login example:

<?php
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://webocreation.com/nepalbuddha/index.php?route=api%2Flogin",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "key=ijLJxZa1kUO8DP4gp0iSHewnDN8zpf7T4c0d8qE3OBZi5sJnkWmi5GQ1UcGR6SttzCtHXv80ImiBGz8saVx5JBrQf5zTmetuSLGjLZNiLDoOWY0zpDQIHWWyh0mr4WATp4HJ3knAiV3G8AE6km0BgY4liu5Uik5w2FKFqkZHldVNOoDaKyOJhp2bCeVqxbDHJpHlv2lECKIBsglLFSZmUmv1e7rpWnyi7HCzyX14Odpq37j4coM5iuspzm3dwloX&username=rupak",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
        "content-type: application/x-www-form-urlencoded",
        "postman-token: 60329eeb-62ad-78e6-f564-486a6a1fe051"
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

If authentication was successful, a 32-character hexadecimal API token will be returned in the following format:

{"success":"Success: API session successfully started!","api_token":"10f6607afd57b954a853f7ce29"}

Example Curl POST Request in OpenCart API:

curl -X POST \
  'https://webocreation.com/nepalbuddha/index.php?route=api%2Flogin' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'postman-token: 2ef6e7f4-84d1-28ae-84b0-ae2dcebeab2f' \
  -d 'key=ijLJxZa1kUO8DP4gp0iSHewnDN8zpf7T4c0d8qE3OBZi5sJnkWmi5GQ1UcGR6SttzCtHXv80ImiBGz8saVx5JBrQf5zTmetuSLGjLZNiLDoOWY0zpDQIHWWyh0mr4WATp4HJ3knAiV3G8AE6km0BgY4liu5Uik5w2FKFqkZHldVNOoDaKyOJhp2bCeVqxbDHJpHlv2lECKIBsglLFSZmUmv1e7rpWnyi7HCzyX14Odpq37j4coM5iuspzm3dwloX&username=rupak'

Example curl GET request in Opencart API:

curl -X GET \
'https://webocreation.com/nepalbuddha/index.php?route=api%2Fcart%2Fproducts&api_token=10f6607afd57b954a853f7ce29' \
-H 'cache-control: no-cache' \
-H 'postman-token: 969b0a8f-aa76-5ec5-10f5-a5f768a2868d'

Here api_token=YOUR_TOKEN_VALUE

It will give the following results when there are no products:

{
    "products": [],
    "vouchers": [],
    "totals": [
        {
            "title": "Sub-Total",
            "text": "$0.00"
        },
        {
            "title": "Total",
            "text": "$0.00"
        }
    ]
}

Similarly, you can use the following API end points:

  • index.php?route=api/login
  • index.php?route=api/cart/add
  • index.php?route=api/cart/edit
  • index.php?route=api/cart/remove
  • index.php?route=api/cart/products
  • index.php?route=api/coupon
  • index.php?route=api/currency
  • index.php?route=api/customer
  • index.php?route=api/order/add
  • index.php?route=api/order/edit
  • index.php?route=api/order/delete
  • index.php?route=api/order/info
  • index.php?route=api/order/history
  • index.php?route=api/payment/address
  • index.php?route=api/payment/methods
  • index.php?route=api/payment/method
  • index.php?route=api/reward
  • index.php?route=api/reward/maximum
  • index.php?route=api/reward/available
  • index.php?route=api/shipping/address
  • index.php?route=api/shipping/methods
  • index.php?route=api/shipping/method
  • index.php?route=api/voucher
  • index.php?route=api/voucher/add

Above all, please see this post, how you can get all products through API in OpenCart. Please let us know if you have any questions, suggestions and follow us at twitter @rupaknpl and subscribe to our youtube channel Opencart tutorials where you can see OpenCart tutorials for beginners to advance programmers.

OpenCart error FTP needs to be enabled in the settings

This is a solution for the OpenCart error FTP needs to be enabled in the settings. Navigate to System >> Settings >> then edit store where you want to enable the FTP

Then click FTP tab

how to enable ftp in opencart
  • Enter FTP host usually “localhost”, but make sure it is correct from your hosting.
  • Enter port usually “21”, but make sure it is correct from your hosting
  • Enter FTP username
  • Enter FTP password
  • Enter the root folder path of your hosting
  • Then choose Yes to enable FTP
  • Finally, save  it

You are set and your FTP is enabled.

Host your NextJs project for free, local to GitHub to hosting, continuous deployment setting

0

In this post, we are showing you how to create and host the NextJs project for free with GitHub flow to hosting and add your domain name. The NextJs is a react framework that is production-ready, pre-rendered, and light-weight apps, the Jamstack(JavaScript, APIs, and markup stack), SEO-friendly, PWAs, and mobile-ready. We set up a GitHub project, then set up the local environment, and then setup Vercel hosting where the master branch is continuously deployed. A domain is added for the master branch and you can add the dev and test environment by creating the branches in the Github project.

  • First, register your domain name. It can cost you around $8-$10 and some countries provide it free also, like in Nepal if you register as per your name then it is free like mine is rupaknepali.com.np.
  • Second, create a GitHub account if you don’t have by going to https://github.com/join and then create a repository in GitHub. In the below example the repository name is “ebookdesign”
Github repository creation
  • Setup a local development environment. Install NodeJs, Github, IDE(we use Visual Studio code),
  • Now, in the terminal create a folder like for us we create “ebookdesign“, go or ‘cd’ to the project folder, and clone the GitHub project that we create above in the Github. Use your project URL.
git clone https://github.com/webocreation-rupak/ebookdesign.git .
  • After you cloned it, run following command
npm init -y && npm install --save react react-dom next

This will create the package.son file and install react, react-dom, and next project. Now open the package.json, then remove the following lines of code:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },

Then add following lines of code:

 "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },

Open pages/ folder and create at file named index.js and paste following code:

const Index = () => {
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
};
export default Index;

Now open the project and create pages/ folder and public/ folder, the files and folders till now are like below:

Files and folders structure of NextJs

Now in terminal run command

npm run dev

It will start the server on http://localhost:3000 and compile code successfully. You can open the URL http://localhost:3000 in your browser and you can see the “Hello World” page, which means you did all good till now.

Now push this code changes in the github project.

git add . && git commit -m "pages folder and public folder are created" && git push origin master

Now go to https://vercel.com/signup and click the button “Continue with GitHub”. Then you authorize the Vercel to Github.

Authorize Vercel with Github

You will get the popup to enter your mobile number for the verification process. After verification with mobile code, you are redirected to the welcome page where you need to enter your details.

Welcome message of NextJs integration

Import github repository

Importing git repository on NextJs

Enter the URL of your Github repository and click “Continue”

Importing git repository on hosting

Install Vercel to Github and give access to your repositories

Install Vercel on github

Then, in the next screen you can click the deploy the project and if everything is Ok then your project is successfully added.

Successful setup of continuous integrations from github to NextJs

You will get the url like https://ebookdesign.vercel.app/

Now let’s add our domain to the project, for that, go to Settings at the top menu and then in the domain and add the domain name.

Domain name settings in NextJs

https://vercel.com/docs/custom-domains#dns-records

After adding the domain you will get the DNS records which you need to add on your domain registrar.

Domain name delegates

With these changes you can visit through your URL, here we are using dpsignadvertising.com

The easy part using the Vercel, we can create as many demo website as we want, each branch of your Github project. Let create one branch in our local called dev and push it to github and it will automatically show at the hosting.

git checkout -b dev
git add .
git commit -m "Dev branch test"
git push origin dev

Once above command is run, then we will get the “Preview Deployments” like below at Project >> Overview, it gives us the URL like https://ebookdesign-orz1lbra5.vercel.app/

Dev environment setup on NextJs projects

Check the flow diagram:

NextJs local Github Vercel flow

Now you can make changes to the code and start your development. In our upcoming post, we will show you how to show youtube videos, WordPress posts, and texts. Please let us know if you have any questions or concerns. Hope you liked this article, please subscribe to our YouTube Channel for Opencart video tutorials. Find us on Twitter and Facebook.

Separate register form containing email and password only in OpenCart 2.2

We created files that will show the Separate register form page containing email and password only in OpenCart 2.2.
At our server it is working when we run like index.php?route=account/registerb it is showing as the following images:

register-with-different-form

Download code below:

Download Different Register Page Code

Thanks
Rupak Nepali

OCMOD Modification System opencart 2.3 example for Show all products module eCommerce

In this opencart guide, we are showing you the OCMOD Modification System of Opencart 2.3 with an example of the “Show all products module” eCommerce. Opencart 4 OCMOD documentation

Things to take care of while making an OCMOD file:

  1. File extension must be either .ocmod.zip or .ocmod.xml.
  2. Upload from the admin section, Admin>>Extensions >> Extension Installer, Upload the .xomod.zip or .ocmod.xml file from here.

Now go to the following link and download the “Display all Products” module Download shows all products module You will find the following OCMOD example which shows how to show “All Products” links at the top menu bar.  

For example:

<modification>
<version>OpenCart Version 2.2</version>
<vqmver>2.0.0</vqmver>
<author>Rupak Nepali</author>
   <code>List_all_Products</code>
<file name="catalog/view/theme/*/template/common/header.tpl" error="skip">
<operation>
<search position="after"><![CDATA[
<ul class="nav navbar-nav">
]]></search>
<add><![CDATA[
<li><a href="index.php?route=product/allproduct">All Products</a></li>
]]></add>
</operation>
</file>
</modification>

More details at https://github.com/opencart/opencart/wiki/Modification-System OCMOD is a system that allows store owners to be able to modify their store by uploading a compressed file that contains XML, SQL, and PHP files. If an OCMOD is developed correctly it can modify how a user’s OpenCart store works without changing any of the core files. This means that if a modification is removed none of the original OpenCart files need to be restored or fixed.  

OCMOD Files

OCMOD files can be uploaded via the opencart admin under Extensions / Extension Installer For an OCMOD file to be uploaded the file extension must be either .ocmod.zip or .ocmod.xml. This is to avoid none of the OCMOD files from being uploaded to a store user admin.

File Structure

Example file structure for OCMOD compressed files.

  • upload
  • install.sql
  • install.php
  • install.xml

upload

All files under this directory will be uploaded to the directory of your OpenCart installation.

install.sql

Add any create, drop, insert, and update SQL queries here. Make sure each query ends with ;

install.php

If the modification requires any custom PHP code.

install.xml

The XML modification file. You can view the documentation for this system below.

XML

This is the file that creates a virtual copy of any files that require changes. Use this system instead of overwriting any default installation files. Multiple modifications can be applied to the same file. Example OCMOD file:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Modification Default</name>
    <version>1.0</version>
    <author>OpenCart Ltd</author>
    <link>http://www.opencart.com</link>
    <file path="catalog/controller/common/home.php">
        <operation>
            <search><![CDATA[
            $data['column_left'] = $this->load->controller('common/column_left');
            ]]></search>
            <add position="replace"><![CDATA[
            test123
            ]]></add>
        </operation>
    </file>  
</modification>

Tags

File

You can set multiple file locations by spiting up the file locations using commas. The modification system uses the PHP function glob. http://hk1.php.net/manual/en/function.glob.php Example: Direct file path.

<file path="catalog/controller/common/home.php">

Using braces allows for selecting multiple files and not having to repeat the code operation multiple times.

<file path="system/engine/action.php|system/engine/loader.php|system/library/config.php|system/library/language.php">

also allows braces

<file path="system/{engine,library}/{action,loader,config,language}*.php">

please note that all file paths must start with either admin, catalog, or system. you can also use wildcard *

Search

Search code Allowed Attributes

  • trim=”(true|false)”
  • regex=”(true|false)”
  • index=”(number)”

Example:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Modification Default</name>
    <version>1.0</version>
    <author>OpenCart Ltd</author>
    <link>http://www.opencart.com</link>
    <file path="catalog/controller/common/home.php">
        <operation>
            <search trim="true|false" index="1"><![CDATA[
            $data['column_left'] = $this->load->controller('common/column_left');
            ]]></search>
            <add position="replace" offset="1"><![CDATA[
            test123
            ]]></add>
        </operation>
    </file>  
</modification>

Add

The code to replace the search with. Allowed Attributes

  • trim=”(true|false)”
  • position=”(Replace|Before|After)”
  • offset=”(number)”

(note position can not be used if regex is set to true in the search attribute). Example

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Modification Default</name>
    <version>1.0</version>
    <author>OpenCart Ltd</author>
    <link>http://www.opencart.com</link>
    <file path="catalog/controller/common/home.php">
        <operation>
            <search trim="true|false"><![CDATA[
            $data['column_left'] = $this->load->controller('common/column_left');
            ]]></search>
            <add position="Replace|Before|After" trim="true|false" offset="2"><![CDATA[
            test123
            ]]></add>
        </operation>
    </file>  
</modification>
Regex

Allowed Attributes

  • limit=”(number)”

Example:

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Regex Example</name>
    <version>1.0</version>
    <author>OpenCart Ltd</author>
    <link>http://www.opencart.com</link>
    <file path="system/{engine,library}/{action,loader,config,language}*.php">
        <operation>
            <search regex="true" limit="1"><![CDATA[
            ~(require|include)(_once)?\(([^)]+)~
            ]]></search>
            <add><![CDATA[
            $1$2(modification($3)
            ]]></add>
        </operation>
    </file>
</modification>

If you use regex you can not use attributes position, trim or offset as these are handled by the regular expression code you write. The limit attribute is still available. If, for example, you want to change the 3rd ‘foo’ to ‘bar’ on the following line:

lorem ifoopsum foo lor foor ipsum foo dolor foo
^1      ^2      ^3         ^4        ^5

Run:

s/\(.\{-}\zsfoo\)\{3}/bar/

Result:

lorem ifoopsum foo lor barr ipsum foo dolor foo
^1      ^2      ^3=bar     ^4        ^5

You can find more information about the regular expression PHP function OCMOD uses can be found here: http://hk2.php.net/manual/en/function.preg-replace.php More information about regular expression can be found here: http://www.regular-expressions.info

How to add a google map in Contact us page of OpenCart? – no coding needed

This OpenCart tutorial shows you how to add a google map to the contact us page of OpenCart without coding or programming knowledge, we will show you how to use the HTML content default OpenCart module and add the map to the contact us page.

Let’s get started by going to https://google.com/maps then searching your locations in it. Once you find the location

Find the location in google map

When you click the “Share” icon you will see a popup click “Embed a map” then click “Copy HTML”

Google map embed code

Now go to your store OpenCart admin >> Extensions >> Extensions >> Choose the extension type “Modules” >> Then scroll to see the “HTML Content”. If you see the green button here, first click to install it.

Add HTML content module for google map

Then, click the blue button to add a new module.

Google map embed code
  • Enter the module name in “Module Name” field
  • Enter the title that you want to show in the front-end, you can leave it blank if you don’t need
  • Click the “Source Code” icon
  • Paste the google map HTML code
  • If you want full-width map then you have to change the width to 100%
  • Again click the Source code icon
  • Then click Save button

Now go to Admin >> Design >> Layouts >> Edit “Contact” then add the Google Map module in your desired position.

Then click save and see your front end.

You can see our demo here:

See Demo of Google map in Contact us page of OpenCart

Let us know if need any help