Hiding Blocks on Magento Sites for Mobile Devices
Hiding specific blocks or content areas when your Magento site is viewed on mobile devices can greatly improve the user experience by reducing clutter and load times. In this guide, we’ll explore how to achieve this using both the built-in CMS and custom PHP code.
Using the Built-In CMS
Magento’s default theme comes with a simple way to hide blocks from mobile view using the CMS. Here’s how:
- Navigate to your Magento admin panel.
- Click on the “Content” menu, then select “Pages”.
- Find the page where you want to hide the block and click “Edit”.
- In the “Page Content” section, click the “Show / Hide Editor” button to enable the WYSIWYG editor.
- Find the block in your content that you want to hide (it will look like
<block type="cms/block" block_id="789">). - Add
<!--[if !IE 7]><!--><style type="text/css">#block_789 {display: none;}</style> <!--<![endif]-->immediately after the opening<div class="block-content">tag. - Save and preview your page.
This technique uses a conditional comment to apply CSS styles only in modern browsers, while old Internet Explorer versions ignore it. The hidden block will not be displayed on mobile devices due to their smaller screen sizes.
Using Custom PHP Code
For more complex requirements, you may need to use custom PHP code to hide specific blocks based on the device type. Here’s an example of how to do this in a Magento layout file:
- Create a new XML layout file (e.g.,
local.xml) located at<your_magento_root>/app/design/frontend/default/<your_theme_name>/layout. - Add the following code within the
<default>tag:
<reference name="content">
<block type="cms/block" block_id="789" template="cms/empty.phtml" ifconfig="{'mobile_detect': 1}" />
</reference>
- In your theme, create a new file named
mobile_detect.phplocated at<your_magento_root>/app/code/local/<Your_Namespace>/<Your_Module>/etc/config.xml. - Add the following code within the
<config>tag:
<default><mobile_detect>
<value>0</value>
</mobile_detect></default>
- Create or modify an existing file named
Mobile_Detect.phplocated at<your_magento_root>/app/code/local/<Your_Namespace>/<Your_Module>/controllers/Observer/Mobile_Detect.php. - Add the following code within the
public function mobileDetect($observer)method:
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false) {
Mage::getConfig()->saveConfig('mobile_detect', 1);
}
- Save all files and clear your cache.
This custom code uses the Mobile_Detect library to identify mobile devices, then sets a configuration value (mobile_detect) accordingly. The layout file checks for this value and hides the specified block if it’s set to 1.
Remember that hiding content on mobile devices should be done judiciously to maintain the overall integrity of your site’s design and user experience.
For more advanced customizations and theme development tips, be sure to check out our comprehensive guides at LaravelCompany.