search
HomeCMS TutorialWordPressEnhance navigation in your WordPress theme: Convert static HTML

If you have followed this series, you now have a working theme with template files uploaded to WordPress. In this tutorial, you'll continue working with the header.php file you created in Part 2. You will learn how to add a navigation menu that is editable through the WordPress menu admin screen. To do this, you will also need to create a new file for your theme: the function file.


What do you need

To complete this tutorial you will need the following:

  • Code Editor of Your Choice
  • Browser for testing your work
  • Local or remote WordPress installation
  • If you are working locally, you will need MAMP, WAMP, or LAMP to run WordPress.
  • If you work remotely, you will need to access your website via FTP and have an admin account on your WordPress installation.

1.Registration Navigation Menu

To register a navigation menu, use the register_nav_menu() function, which you need to add to your theme's functions.php file.

Since your theme doesn't already have this file, you'll want to create one first.

In the theme folder, create a new blank file named functions.php.

Open the new file and add the following content to it:

<?php
function wptutsplus_register_theme_menu() {
    register_nav_menu( 'primary', 'Main Navigation Menu' );
}
add_action( 'init', 'wptutsplus_register_theme_menu' );
?>

You just created your theme’s first feature, so give yourself a pat on the back!

The function you created is named wptutsplus_register_theme_menu(), I added the wptutsplus prefix to the beginning of its name to ensure that the name is unique and does not match any of the registered Other functions conflict through plugins you may be running on your site.

This function includes register_nav_menu() WordPress function, used to create menus. Your function will then be activated via the init action hook, which means WordPress will run your function on initialization.

NOTE: You must activate such functions via the correct hook, otherwise they will not work.

register_nav_menu()The function has two parameters:

  • One of these parameters includes the location of the menu. In this example, we'll call that location 'primary'. You will add this to your header.php file later so WordPress displays the correct menu.
  • The second parameter is the description of the menu. In this case, 'Main Navigation Menu'. This will be visible in the Menu admin screen.

2. Set navigation menu

You now have access to the Menu dashboard screen, which was previously unavailable because your theme did not have a registered menu. It's not perfect at the moment, but we'll change it soon:

增强 WordPress 主题中的导航:转换静态 HTMLEnhance navigation in your WordPress theme: Convert static HTML增强 WordPress 主题中的导航:转换静态 HTML

As you create pages, posts, and other content, you can add them to the navigation menu from this screen. I will add two new pages called "Blog" and "About". I will specify the Blog page as the page where my posts will appear via the Settings screen. You can create any page you like.

After completing this operation, return to the "Menu" screen to edit the menu and add a new page. After dragging the new page to the menu, click Create Menu to create the new menu.

Finally, check "Main Navigation Menu" under "Theme Location" to ensure that the menu will appear as the main menu you just registered and save the menu.

增强 WordPress 主题中的导航:转换静态 HTMLEnhance navigation in your WordPress theme: Convert static HTML增强 WordPress 主题中的导航:转换静态 HTML

NOTE: Always remember to save your menu after making any changes to it - unlike widgets, WordPress does not automatically save menus.


3. 将菜单添加到您的主题

目前,此菜单在您的网站上仍然不可见;您需要将菜单添加到头文件中才能实现此目的。

打开主题的 header.php 文件并找到以下代码:

<nav class="menu main">
    <?php /*  Allow screen readers / text browsers to skip the navigation menu and get right to the good stuff */ ?>
    <div class="skip-link screen-reader-text">
        <a title="Skip to content" href="#content">Skip to content</a>
    </div>
    <ul>
        <li>
            <a href="#">Home</a>
        </li>
        <li>
            <a href="#">Latest news</a>
        </li>
        <li>
            <a href="#">Featured articles</a>
        </li>
    </ul>
</nav><!-- .main -->

并将其替换为:

<nav class="menu main">
    <?php /*  Allow screen readers / text browsers to skip the navigation menu and get right to the good stuff */ ?>
    <div class="skip-link screen-reader-text">
        <a title="Skip to content" href="#content">Skip to content</a>
    </div>
    <?php wp_nav_menu( array( 'container_class' => 'main-nav', 'theme_location' => 'primary' ) ); ?>
</nav><!-- .main -->

这将添加您在主题中的此位置注册的导航菜单,使用 wp_nav_menu() 函数并指定 'primary' (您在注册时为菜单指定的位置)为'主题位置'

这现在反映在我网站的导航菜单中:

增强 WordPress 主题中的导航:转换静态 HTMLEnhance navigation in your WordPress theme: Convert static HTML增强 WordPress 主题中的导航:转换静态 HTML

摘要:菜单不仅仅用于网站标题!

在本教程中,您学习了如何注册导航菜单、向其中添加项目以及将其添加到网站标题。

需要注意的是,菜单不仅仅必须位于网站标题中。您可以在多个位置添加菜单,包括:

  • 侧边栏 - 可能是网站某个部分的部分菜单或当前页面的子页面列表
  • 页脚 - “小字体”页面或最常访问的页面的菜单。
  • 在主导航下方 - 也许是主导航下方的部分菜单。

您可以通过三种方式之一在主题中的更多位置添加菜单。

我按照难度升序列出了它们:

  • 通过“菜单”管理屏幕创建额外的菜单,然后使用“自定义菜单”小部件将它们显示在主题中具有小部件区域的任何位置
  • 通过“菜单”管理屏幕创建额外的菜单,然后将它们添加到主题的代码中,如上面所做的那样。在本例中,您向 wp_nav_menu() 函数调用的数组添加一个附加参数,指定 'menu' 参数作为您为创建的每个菜单指定的名称。
  • 使用 register_nav_menus() 函数注册多个菜单,并将它们添加到主题中的相关位置,如上所述

为什么不尝试一下呢?


资源

  • 导航菜单指南
  • register_nav_menu() 函数
  • wp_nav_menu() 函数

The above is the detailed content of Enhance navigation in your WordPress theme: Convert static HTML. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does WordPress compare to other website builders?How does WordPress compare to other website builders?Apr 28, 2025 am 12:04 AM

WordPressexcelsoverotherwebsitebuildersduetoitsflexibility,scalability,andopen-sourcenature.1)It'saversatileCMSwithextensivecustomizationoptionsviathemesandplugins.2)Itslearningcurveissteeperbutofferspowerfulcontroloncemastered.3)Performancecanbeopti

5  WordPress Plugins for Developers To Use in 20255 WordPress Plugins for Developers To Use in 2025Apr 27, 2025 am 08:25 AM

Seven Must-Have WordPress Plugins for 2025 Website Development Building a top-tier WordPress website in 2025 demands speed, responsiveness, and scalability. Achieving this efficiently often hinges on strategic plugin selection. This article highlig

What would you use WordPress for?What would you use WordPress for?Apr 27, 2025 am 12:14 AM

WordPresscanbeusedforvariouspurposesbeyondblogging.1)E-commerce:WithWooCommerce,itcanbecomeafullonlinestore.2)Membershipsites:PluginslikeMemberPressenableexclusivecontentareas.3)Portfoliosites:ThemeslikeAstraallowstunninglayouts.Ensuretomanageplugins

Is WordPress good for creating a portfolio website?Is WordPress good for creating a portfolio website?Apr 26, 2025 am 12:05 AM

Yes,WordPressisexcellentforcreatingaportfoliowebsite.1)Itoffersnumerousportfolio-specificthemeslike'Astra'foreasycustomization.2)Pluginssuchas'Elementor'enableintuitivedesign,thoughtoomanycanslowthesite.3)SEOisenhancedwithtoolslike'YoastSEO',boosting

What are the advantages of using WordPress over coding a website from scratch?What are the advantages of using WordPress over coding a website from scratch?Apr 25, 2025 am 12:16 AM

WordPressisadvantageousovercodingawebsitefromscratchdueto:1)easeofuseandfasterdevelopment,2)flexibilityandscalability,3)strongcommunitysupport,4)built-inSEOandmarketingtools,5)cost-effectiveness,and6)regularsecurityupdates.Thesefeaturesallowforquicke

What makes WordPress a Content Management System?What makes WordPress a Content Management System?Apr 24, 2025 pm 05:25 PM

WordPressisaCMSduetoitseaseofuse,customization,usermanagement,SEO,andcommunitysupport.1)Itsimplifiescontentmanagementwithanintuitiveinterface.2)Offersextensivecustomizationthroughthemesandplugins.3)Providesrobustuserrolesandpermissions.4)EnhancesSEOa

How to add a comment box to WordPressHow to add a comment box to WordPressApr 20, 2025 pm 12:15 PM

Enable comments on your WordPress website to provide visitors with a platform to participate in discussions and share feedback. To do this, follow these steps: Enable Comments: In the dashboard, navigate to Settings > Discussions, and select the Allow Comments check box. Create a comment form: In the editor, click Add Block and search for the Comments block to add it to the content. Custom Comment Form: Customize comment blocks by setting titles, labels, placeholders, and button text. Save changes: Click Update to save the comment box and add it to the page or article.

How to copy sub-sites from wordpressHow to copy sub-sites from wordpressApr 20, 2025 pm 12:12 PM

How to copy WordPress subsites? Steps: Create a sub-site in the main site. Cloning the sub-site in the main site. Import the clone into the target location. Update the domain name (optional). Separate plugins and themes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.