Simplify the process of creating mega menus in WordPress
Aug 30, 2023 pm 11:01 PMIn my previous article, I looked at how to determine when a mega menu is right for your site and how to use a plugin to create a mega menu.
But if you're feeling more ambitious, you might prefer to code your own mega menu into your theme. This gives you the benefit of being able to design your menu the way you want and ensure it goes with your theme.
In this tutorial I will show you how to write a mega menu and add it to your theme.
what do you need
To follow this tutorial you will need the following:
- Development installation of WordPress (don’t add it to your live site until everything is running properly).
- A theme that you can edit yourself, or if you are using a third-party theme, a child theme of that theme.
- Code Editor.
I am using a third party theme (ColorMag) so I will create a child theme for it and add my styles to it.
How Mega Menu Works
Our mega menu will take the code output by the menu system in WordPress and display it as a mega menu. I wouldn't add an extra menu to the site: you can do that if you want, but since this large menu won't work on smaller screens, I prefer to stick with the same menu. This is because I like to give users on mobile and desktop access to the same navigation.
Mega menu styles will only work on larger screens. For smaller screens, I recommend using a hamburger menu, which is invisible until the user clicks on the hamburger (three horizontal lines) icon. You can learn how to code a hamburger menu in our hamburger menu coding tutorial.
start using
The first step is to add a large number of menu items to the menu. This means you'll have plenty of content to populate your mega menu.
I added a lot of links to the menu and have three levels of navigation. When the user hovers over a top-level menu item, the items below that menu item appear in the mega menu. They now appear in the standard layout:
Let us first identify the code output by this menu on the front end of the website. Here is the (edited) code for my menu. I took out some li
elements and removed most of the CSS classes so you can see the structure of the HTML:
<nav id="site-navigation" class="main-navigation clearfix" role="navigation"> <div class="inner-wrap clearfix"> <p class="menu-toggle"></p> <div class="menu-primary-container"> <ul id="menu-main-nav" class="menunav-menu" aria-expanded="false"> <li><a>Home</a></li> <li> <a>Top Level Item</a> <ul class="sub-menu"> <li><a>Second Level Item 1</a> <ul class="sub-menu"> <li><a>Third Level Item 1</a></li> <!-- more li elements --> </ul> </li> <li> <a>Second Level Item 2</a> <ul class="sub-menu"> <li><a>Third Level Item 5</a></li> <!-- more li elements --> </ul> </li> <li><a>Second Level Item 3</a> <ul class="sub-menu"> <li> <a>Third Level Item 7</a> </li> <!-- more li elements --> </ul> </li> </ul> </li> <li> <a>Another Top Level Item</a> <ul class="sub-menu"> <li> <a>Second Level Item 4</a> <ul class="sub-menu"> <li><a>Third Level Item 12</a></li> <!-- more li elements --> </ul> </li> </ul> </li> </ul> </div> </div> </nav>
There's a lot of code there, but I recommend spending some time studying it, as it can help us identify the classes and elements (and sub-elements) we need to position using CSS in order to create our mega menu.
We can use WordPress-generated CSS classes to design our mega menu and ensure it is laid out correctly. We'll use media queries to ensure that the menu only appears on screens that are large enough.
The specific elements we will target are:
.main-navigation
-
ul
elements (includingul ul
andul ul ul
) -
The
li
anda
elements are inside the ul element.
On smaller screens I would make the default menu visible, although on very small screens I would recommend using mobile alternatives such as a hamburger menu. My theme already has a hamburger menu coded for small screens, so I don't need to worry about that.
Note: Your theme’s HTML output will be similar to mine because it is generated by WordPress. But there can also be differences, such as the class or ID of the main navigation element. To be sure, it’s best to check first.
Set media query
The first step is to add media queries for the mega menu style (if needed). In your theme's stylesheet, add the following:
@media screen and ( min-width: 500px ) { }
You can change the min-width
value to one that is appropriate for your theme and corresponds to any existing media queries for the hamburger menu.
Set layout style
My existing menu is styled in such a way that the third level items only show up when I hover over the second level items immediately above them. I want to change this so that all menu items are displayed. Then I'll style them so they lay out correctly.
Let's start by making the second and third level menu items visible when the user hovers over the top level menu item.
Add this to the stylesheet inside the media query:
.main-navigation ul:hover li ul, .main-navigation ul:hover li ul li ul { display: inherit; }
Now, when you refresh the page and hover over the menu item, it will look a little like this:
第二層和第三層的項(xiàng)目是可見的,但說得客氣一點(diǎn),它們看起來很亂。讓我們解決這個(gè)問題。
我們首先將每個(gè)頂級(jí)項(xiàng)目下的 li
元素設(shè)置為全寬。為了實(shí)現(xiàn)這一點(diǎn),我們必須通過將其設(shè)置為靜態(tài)來刪除上面元素的任何相對(duì)或絕對(duì)定位。我們還將添加 display:inherit
以確保當(dāng)頂級(jí)菜單項(xiàng)懸停在上方時(shí),下級(jí)菜單項(xiàng)可見。
將其添加到您的樣式表中:
.main-navigation { position: relative; } .main-navigation li { position: static; } .main-navigation ul li:hover ul { display: inherit; position: absolute; left: 0; right: 0; width: 100%; } .main-navigation ul li:hover ul li ul { display: inherit; position: relative; left: 0; }
菜單現(xiàn)在看起來像這樣:
它是全寬的,但我們需要做一些改進(jìn)布局。讓我們向二級(jí)列表添加一個(gè)浮動(dòng),以便它們彼此相鄰顯示。
將其添加到您的樣式表中:
.main-navigation ul li:hover ul li { float: left; position: static; display: block; padding-top: 1em; } .main-navigation ul li:hover ul li ul li { float: none; padding-top: 0; }
現(xiàn)在菜單看起來更好了:
浮動(dòng)正在工作,但背景顏色已關(guān)閉。編輯 .main-navigation ul li:hover ul
元素的樣式以添加背景樣式。您使用的具體顏色取決于您使用的主題。
.main-navigation ul li:hover ul { display: inherit; position: absolute; left: 0; right: 0; width: 100%; background-color: #bababa; }
現(xiàn)在菜單看起來更好了:
讓我們?yōu)楦鱾€(gè)列表添加一些顏色和布局樣式,以使第二級(jí)項(xiàng)目更加突出。將其添加到您的樣式表中:
.main-navigation ul:hover ul li a:link, .main-navigation ul:hover ul li a:visited { color: #b01b1b; text-decoration: underline; } .main-navigation ul:hover ul li ul li a:link, .main-navigation ul:hover ul li ul li a:visited { color: #fff; text-decoration: none; }
這使得列表看起來更好,第二級(jí)項(xiàng)目帶有下劃線和紅色。請(qǐng)隨意修改這些顏色以適合您的主題。
最后,讓我們刪除第三級(jí)項(xiàng)目的上邊距,以便它們更緊密地聚集在一起。編輯它們的代碼如下:
.main-navigation ul:hover ul li ul li a { padding-left: 1em; padding-top: 0; }
現(xiàn)在菜單看起來更加整潔:
我們現(xiàn)在有了一個(gè)功能強(qiáng)大的大型菜單,使用我們主題中的主導(dǎo)航菜單。
您不需要插件來創(chuàng)建簡單的超級(jí)菜單
如果您想使用 WordPress 導(dǎo)航菜單的內(nèi)容創(chuàng)建一個(gè)簡單的大型菜單,這種技術(shù)可以讓您將一個(gè)菜單添加到您的主題中,而無需太多額外的代碼。
但是,如果您想添加額外的功能,例如自定義樣式和圖像,使用插件可能會(huì)更快。您一定會(huì)在我們的頂級(jí)大型菜單插件列表中找到滿足您需求的一款。
The above is the detailed content of Simplify the process of creating mega menus in WordPress. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.
