Opencart – implementing a mobile theme

There’s a number of approaches to implementing a mobile theme on Opencart. First off, let’s assume that you’re not just catering for mobiles, and that you want to make different pages available to mobiles.

Option 1 – Use a single responsive theme

In theory it’s possible to serve a single theme which will adapt itself to the screen size used via css media queries. Originally, this approach required too many compromises to result in a good experience all round. Media queries mean that you’re just displaying the page differently, but the html served to the page is identical, and hence there’s no way to avoid serving lots of big images to a mobile (or conversely, serving poor quality images to a desktop browser). With improved mobile networks, this is far less of an issue, and this is now my preferred approach. (The BBC, currently, are serving low quality images and then using js to add better quality images dependent on screen size, resulting in a horrible experience on a desktop. Hum.)

Option 2 – Create a separate store that uses a mobile specific theme

Once you take this step (instructions here) then there are again some options as to how this is implemented. For the purposes of this document I’ll assume a main store set up on http://www.mystore.com and a mobile store on http://m.mystore.com. The mobile store has id=1 within Opencart.

Option 2A – Detect the mobile browser using PHP

There are a number of mobile browser detect scripts out there. These attempt to identify a browser as coming from a mobile from the header information passed from the browser when it calls the page. I tried using the Mobile Detect class. This is simple to use. I stored the Mobile_Detect.php file in the root of my store, and included the following code (in red_ in catalog/controller/common/home.php:

class ControllerCommonHome extends Controller {
	public function index() {
	
		include $_SERVER['DOCUMENT_ROOT'].'/Mobile_Detect.php';
		$detect = new Mobile_Detect();
		if ($detect->isMobile() && !$detect->isTablet() && $this->config->get('config_store_id')!=1){
			header('Location: http://m.mystore.com');
		}	
	
		$this->document->setTitle($this->config->get('config_title'));

So, I’m calling the Mobile_Detect() class, and from the results of that, if it’s a mobile, and if it’s not a tablet, and if it’s not already the mobile store (identified by store_id = 1 here, check your own installation), then I’m redirecting to the mobile store homepage.

This works fine, and redirects all calls to the default store homepage only from a mobile (phone) to the mobile store. You could use similar code in catalog/controller/common/header.php to redirect any page to its mobile equivalent. Something like:

class ControllerCommonHeader extends Controller {
	protected function index() {
	
		include $_SERVER['DOCUMENT_ROOT'].'/Mobile_Detect.php';
		$detect = new Mobile_Detect();
		
		if ($detect->isMobile() && !$detect->isTablet() && $this->config->get('config_store_id')!=1){
			if (isset($this->request->server['HTTPS'])) {
				$mobile_redirect = 'http://m.mystore.com';
			} else {
				$mobile_redirect = 'http://m.mystore.com';
			}
			if ($_SERVER['REQUEST_URI']) $mobile_redirect .= html_entity_decode($_SERVER['REQUEST_URI']);
			header('Location: '.$mobile_redirect);
		}		
			
		$this->data['title'] = $this->document->getTitle();

Here I need to additionally construct the URL to redirect to from the entered URL. I’ve tested this across a number of pages, both with and without SEO URLs, and it seems to work fine. I don’t have access to a test server with SSL enabled, however, so be warned…

A potential issue here is that the customer doesn’t really know what’s happened to them, and worse, they can’t get back to the main store, because they’ll always be redirected. The other downside is that the redirect itself relies on accurately detecting the device from the headers. A glance at the code in Mobile_Detect.php reveals a whole list of device identifiers that is going to become outdated at some point, leading to incomplete redirections. While it’s quite neat (at least at the moment), I’m not keen on the inflexibility.

Option 2B – Detect the mobile browser using javascript

It would be possible to detect the screen width of the browser, and redirect to your mobile store if the width is less than a certain value. If you just want to implement this on your home page, then it’s quite simple – just add the following to your default store home.tpl:

<script type="text/javascript">
if (screen.width <= 699) {
window.location('http://m.oc1531.simonbattersby.com');
}
</script>

If you want to redirect every page it get's messy, and it's easier I think to do some of the work in the controller - you could add the following to catalog/controller/common/header.php:

		if (isset($this->request->server['HTTPS'])) {
			$mobile_redirect = 'http://m.mystore.com';
		} else {
			$mobile_redirect = 'http://m.oc1531.simonbattersby.com';
		}
		if ($_SERVER['PHP_SELF']) $mobile_redirect .= $_SERVER['PHP_SELF'];
		if  ($_SERVER['QUERY_STRING']) $mobile_redirect .= '?'.html_entity_decode($_SERVER['QUERY_STRING']);
		$this->data['mobile_redirect'] = $mobile_redirect;

This is using the same logic to build the redirect URL as above. Then, in your default store header.tpl:

<script type="text/javascript">
if (screen.width <= 699) {
window.location='<?php echo $mobile_redirect;?>';
}
</script>

Using javascript has the advantage that you're just relying on the screen's width, and hence are not dependent on any list of browsers being kept up to date. I'm still not keen on the inflexibility however...

Option 2C - Let the customer choose

You could just let the customer choose which version they want to use...they'll always know if they're using a mobile or not (hopefully).

One way of doing this is to use Opencart's Store module, which will list all your stores and let the customer navigate from one to the other from a drop down menu. You could also just add a manual link (by editing header.tpl) to point at your mobile store.

Tags:

56 responses to “Opencart – implementing a mobile theme”

  1. Simon says:

    The Opencart default theme has been responsive since OC2, so I’m not sure why you’d want to do this on OC3?

  2. mr philip e hutchinson says:

    Hi Simon,
    This looks interesting would the same logic work on opencart 3.0.3.6? Also is there a reason why the redirect is not going on https?
    Thanks
    Phil

  3. Simon says:

    You could use the Store module, with position set to ‘Content Bottom’. If this doesn’t do what you need then you’d need to write custom code to add to your common/footer controller and template.

  4. Shaun says:

    Hi, how can I put a link in the footer to change the view from mobile to full site.

    Thanks

  5. Simon says:

    I’m not quite sure what you’re saying here. Are you suggesting the $_SERVER[‘REQUEST_URI’] should be escaped? I can’t immediately see how the redirect is more vulnerable than just typing in an attack directly.

  6. Hello,

    in the provided code example for catalog/controller/common/header.php, I can find this line:

    if ($_SERVER[‘REQUEST_URI’]) $mobile_redirect .= html_entity_decode($_SERVER[‘REQUEST_URI’]);

    What happens if a malicious user feeds:

    &alert(‘XSS’);

  7. Simon says:

    See this example, flags in the footer control language. If you don’t get this, check your vQmod log for errors, and look at any other mods you have running that might be interfering with the vQmod for the mobile theme. Your main theme works changing from English, but gives a blank page when changing to English, so there’s something not right.

  8. Admin says:

    HOW can i use English and other language simultaniously as like in my desktop theme??? Where is i can change the language in footer???

  9. Simon says:

    If you install a language pack properly the theme supports this, change language in the footer.

  10. Admin says:

    Sir,
    I want to display both English and Other language option as like my desktop theme. How can i do that, please help me.

  11. Simon says:

    Language is not set by the theme but from your admin panel System > Settings > [store] > Local.

  12. Admin says:

    Sir,
    I installed a regional language pack in my online store, when i visit my mobile site, i see nothing about language changing option there. How can i solve it? Please help me sir, i’m not a developer to solve this issue, please help me sir.

  13. Simon says:

    It’s probably your public_html folder. It is the folder that contains the file, typically index.php or index.htm, which is displayed when you enter http://www.yourdomain.com.

  14. mr Ir says:

    hi simon, where is place called ‘DOCUMENT_ROOT’ in my domain like bx.com,placed in folder public_html ?
    where is i place file Dtetct_Mobile.php?
    thank’s

  15. Simon says:

    That looks like you either don’t have vQmod loaded at all, or there’s a problem with it somewhere. If you do have vQmod, check vqmod/vqmod.log on your server for errors.

  16. Kirk says:

    Hi Simon,
    Thank a lot for this work. I tried to get the mobile version started – negativ.
    I have this error message in (i think so) body frame:

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    Notice: Undefined variable: content_top in /webseiten/Webshop/catalog/view/theme/sb_mobile_theme/template/common/header.tpl on line 49
    Notice: Undefined variable: is_home in /webseiten/Webshop/catalog/view/theme/sb_mobile_theme/template/common/header.tpl on line 50
    Notice: Undefined variable: is_home in /webseiten/Webshop/catalog/view/theme/sb_mobile_theme/template/common/footer.tpl on line 1
    Notice: Undefined variable: currency in /webseiten/Webshop/catalog/view/theme/sb_mobile_theme/template/common/footer.tpl on line 27
    Notice: Undefined variable: language in /webseiten/Webshop/catalog/view/theme/sb_mobile_theme/template/common/footer.tpl on line 28
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    what does that mean? how can i fix it?

    thanks so much and in advance πŸ˜‰
    kirk

  17. Simon says:

    No, no redirection – as described here.
    That said, and as my previous reply, the error you are getting suggests there’s something wrong with the subdomain regardless of any redirection.

  18. Thye says:

    Hi Simon,

    Does the subdomain needs to do any redirection? Or just leave it default?

  19. Simon says:

    You should only have one Opencart installation and set of files, as per the instructions, but none of this would explain why the domain is giving you an error – this means there is something wrong with your cPanel setup. Regardless of what you have in your file system, if the domain is set up correctly you should not get the not found error.

  20. Thye says:

    Hi Simon,

    My main store is stored in public_html….so the mobile store i put in public_html too…but i found an extra folder named mobile folder created in the same root folder (public_html)….is there any problem?

  21. Simon says:

    Maybe it’s something to take up with your hosting then – because your m.domain is clearly not set up correctly.

  22. Thye says:

    Hi Simon,

    But I followed exactly all the steps in cPanel…i have checked many times and the set up all correct…but still the same? Any idea where’s the problem?

  23. Simon says:

    If the URL is erroring like that then there’s a problem somewhere with how it’s set up in cPanel.

  24. Thye says:

    Hi Simon,

    Yes…i followed all steps as mentioned above but the page still showing that error when i opened the page directly. And my mobile also shown the same error from the page.
    The page is not blank page…just keeps showing β€˜The page you are looking for is unavailable.’
    Here the image:
    http://img14.imageshack.us/img14/921/pdv7.jpg

    Need help….!!

  25. Simon says:

    Is this an Opencart error, or are you just getting a blank page?
    If the latter, have you set up cPanel and Opencart correctly as detailed here?
    If so, then when you view the mobile store directly using its URL does it display correctly?
    If so, then when you view on a mobile is a redirect taking place?
    And if so to what URL?

  26. Thye says:

    Hi Simon,

    My page keeps show β€˜The page you are looking for is unavailable.’
    Which step I wrongly did?

    Need help..!!

  27. Simon says:

    As I said, both the link to Mobile Detect, and the code that you need to use (not that which you posted) is given above.

  28. Thye says:

    Hi Simon,

    Where should I put this code?

    [code sample deleted]

    Need help..!! πŸ™‚

  29. Thye says:

    Hi Simon,

    Download this one?
    http://mobiledetect.net/

  30. Simon says:

    If you look at section 2A above it gives the code you need, plus download the Mobile Detect script and save it on your server.

  31. Thye says:

    Hi Simon,

    I ‘m not sure good in coding…can I have the sample of the code?
    Need your help.

    Thank you πŸ™‚

  32. Simon says:

    Thye

    The mobile detect script is linked from this page – you can find the code there.

  33. Thye says:

    Hi Simon,

    Where I can get the mobile_detect.php file?
    Can I have the code?

    Thank you πŸ™‚

  34. Simon says:

    I can’t help you with this, it’s not my code.

  35. Admin says:

    The js file i used in my code is:-

    function DM_redirect(MobileURL, Home){
    try {
    // avoid loops within mobile site
    if(document.getElementById(“dmRoot”) != null)
    {
    return;
    }
    var CurrentUrl = location.href
    var noredirect = document.location.search;
    if (noredirect.indexOf(“no_redirect=true”) < 0){
    if ((navigator.userAgent.match(/(iPhone|iPod|BlackBerry|Android.*Mobile|BB10.*Mobile|webOS|Windows CE|IEMobile|Opera Mini|Opera Mobi|HTC|LG-|LGE|SAMSUNG|Samsung|SEC-SGH|Symbian|Nokia|PlayStation|PLAYSTATION|Nintendo DSi)/i)) ) {

    if(Home){
    location.replace(MobileURL);
    }
    else
    {
    location.replace(MobileURL + "?url=" + encodeURIComponent(CurrentUrl));
    }
    }
    }
    }
    catch(err){}
    }

  36. Simon says:

    Looks like I had an extra closing bracket in my code snippet, now corrected. The first line of the statement in catalog/controller/home.php should be:

    if ($detect->isMobile() && !$detect->isTablet() && $this->config->get('config_store_id')!=1){
  37. Admin says:

    After successfully insert mobile_detect.php in public_html file and the code in catalog/controller/common/home.php my site show this error:- Parse error: syntax error, unexpected T_BOOLEAN_AND in /home/ebozajk3/public_html/catalog/controller/common/home.php on line 6

    Thats why i again remove this codes. How can i solve it?

  38. Simon says:

    Don’t know what else I can suggest, sorry. I’ve tested all the code on this page and it works for me.

  39. Admin says:

    I used both your redirect code in my store but none is working for me, so i again delete the code. When i used PHP, nothing happened the PC version show as like before and when i used JS and test it in my mobile with opera, it redirect to mobile site but not completely, everytime when i try it, it shows loading all the time. Please Simon, i need a help in this matter from you.

  40. Simon says:

    Are you using javascript to detect the screen width? And it works on every other page but that one? That suggests the script is either not loaded on that page or there’s something else on that page which is causing the js to fail.

  41. Admin says:

    After all kind test by my own self, i decided to remove some particular extension from my default store and i do it. After it my mobile site working great except the ABOUT US page, if i open this page in default browser of mobile, it working great but if i open it in OPERA MOBILE / OPERA MINI browser it shows desktop view not mobile view, why? How can i solve it?

  42. Simon says:

    Like I said, this is apparently being caused by another extension, of which I have no knowledge. I can’t tell you anything more than I already have in comment 11.

  43. Admin says:

    In my previous question about stop cloud zoom in my mobile site, i solved it by myself but can’t solve the other problem about create double image in the additional product which are viewed below the main image. You told me that edit my VQMOD XML file would be solved my problem. Please give me the edited line with instruction about where to put it. Please help me.

  44. Simon says:

    Same way as from any other theme, as described here.

  45. Admin says:

    How can i redirect from my custom theme to my mobile site?

  46. Simon says:

    One to take up with the extension developer really, but I’m guessing that the vQmod file is adding some code to the template files – maybe footer.tpl. You’d need to edit the vQmod xml file such that it doesn’t edit any file in the mobile theme. Again I’m guessing, but it’s probably editing /theme/*/template/common/footer.tpl to pick up the file from any theme. You could specifically target your non-mobile theme only by changing these statement(s) to /theme/default/template/common/footer.tpl. If it’s not footer.tpl, look for another template file that’s being modified.

  47. Admin says:

    I’m applied jquary zoom extension (VQMOD) in my default store but it works on my mobile site too. How can i stop it in my mobile site? In my mobile product page after install the extension it makes all the images double but not in Default store, how can i solve it? My mobile site is:- m.e-bozar.com

  48. Simon says:

    I’ve given the code above. Make you sure you include this in header.tpl for your main, not mobile, store and replace the location with you own URL.

  49. Admin says:

    Then tell me exactly what code and where it would be put?

  50. Simon says:

    I can see no script on e-bozar.com that would redirect.
    Works for me, sorry.

  51. Admin says:

    Redirect code (javascript) not working. Give me a easy procedure.

  52. Admin says:

    Sorry JAVASCRIPT.

  53. Simon says:

    The code here is PHP and javascript (not java which is entirely different). I’m still not sure what it is you’re asking however, that isn’t covered here.

  54. Admin says:

    Just simply tell me about using first box code then the third box code or other in redirecting through JAVA.

  55. Simon says:

    I don’t know java at all, I’m afraid. Slightly curious as to why you’d want to use java to do this, but still…

  56. Admin says:

    Please give me easy method about JAVA redirect system for my opencart 1.5.5.1 store.

Useful? Interesting? Leave me a comment

I've yet to find a way of allowing code snippets to be pasted into Wordpress comments - so if you're trying to do this you'd be better off using the contact form.