I introduced you to "How to create a theme navigation menu in WordPress (1)". This article will continue to introduce you to how to create a theme navigation menu in WordPress. I hope it will be helpful to you!

The previous tutorial talked about how to use WordPress’s built-in functions to create navigation menus, but the HTML codes generated by these functions are fixed, making it difficult for you to define navigation. The HTML code for the menu. This article will introduce you to a few freer ways to create navigation menus that can be used for more than just navigation menus. Of course, this article only provides you with an idea to solve the problem. It is not a tutorial like a recipe. Once you read it and copy it, you can use it in your project.
1. Use get_terms() to get the category list
Use get_terms() to get your article categories, link categories and customizations Categories, etc., passing the corresponding parameters to get_terms() can return you an object array. This array is all the categories you want. The following is the function prototype of get_terms():
<?php get_terms( $taxonomies, $args ) ?>
$taxonomies:
This parameter is the classification category you want to obtain. Optional values include: "category", "link_category", "my_taxonomy", which respectively represent article classification, link classification and Your customized classification, where my_taxonomy is your customized classification name.
$args:
This parameter is the filtering parameter of the category, used to control the acquisition of the category you want to obtain, including how many categories you want to obtain, how to sort, and the parent category And whether to output empty categories, etc. For details, please refer to WordPress official documentation: Function Reference/get terms, or refer to the brief translation in Chinese: Common functions-get_terms()
The following is an example of using this function. Here, an unordered list in the form of
- .. ..
<ul id="menu">
<?php
// 获取分类
$terms = get_terms('category', 'orderby=name&hide_empty=0' );
// 获取到的分类数量
$count = count($terms);
if($count > 0){
// 循环输出所有分类信息
foreach ($terms as $term) {
echo '<li><a href="'.get_term_link($term, $term->slug).'" title="'.$term->name.'">'.$term->name.'</a></li>';
}
}
?>
</ul>The get_terms() function returns an object array $terms. We first determine whether the array is empty. If it is empty, it means that no category has been obtained. If If it is not empty then you can output the classification. Each array item of $terms is an object. The meanings of some object attributes are: slug: category abbreviation, name: category name, term_id: category id. As shown in the above code, you can get the attribute value of the object through $term->name.
2. Use the method of reading the database to obtain the classification list
If you know the WordPress database, you can find that WordPress classification information is stored in wp_terms and wp_term_taxonomy. In the table, wp_terms stores basic information (including article classification, article tags, link classification, etc.), and wp_term_taxonomy is used to store further descriptions (used to store descriptions, distinguish categories and tags, etc.). We can use SQL to get the list of categories we want from these two tables:
<ul id="menu">
<?php
$cats = $wpdb->get_results("SELECT {$wpdb->prefix}terms.term_id, name
FROM {$wpdb->prefix}term_taxonomy, {$wpdb->prefix}terms
WHERE {$wpdb->prefix}term_taxonomy.term_id = {$wpdb->prefix}terms.term_id
AND taxonomy = 'category'");
if($cats) {
foreach($cats as $cat) {
echo '<li><a href="'.get_category_link($cat->term_id).'" title="'.$cat->name.'">'.$cat->name.'</a></li>';
}
}
?>
</ul>3. How to get the id of the current category
Sometimes we need to make a sub-navigation, such as the human resources navigation on the left of http://www.nashowgroup.com/?p=58&lang=zh. This navigation can be any item, such as the current category subcategories under or articles under the current category, etc. So the first question is, how to get the ID of the current category so that we can take the next step.
Get the id of the current category on the category page:
if ( is_category() ) {
$cat_id = get_query_var('cat');
}Get the first category of the article on the article page:
$cats = get_the_category();
if($cats)
$cat_id = $cats[0]->cat_ID;四、子导航的制作
上面我们讲解了如何获取当前分类的id,下面我们来讲讲如何制作子导航。首先,我们来制作一个当前分类下子分类的子导航,这里用到wp_list_categories()来列出子分类,当然你可以用我前面介绍的两种方法来获取分类。:
<ul> <?php // 这里我们用到上面获取到的$cat_id,获取该分类下的所有子分类 wp_list_categories('orderby=name&hide_empty=0&child_of=' . $cat_id); ?> </ul>
如果你的网站规模比较小,一个分类下的文章也不多,那么你可以在子导航中列出这个分类下的所有文章:
<ul> <?php global $wp_query; $query = array ( 'cat' => $cat_id, 'orderby' => title, 'order'=> ASC ); $queryObject = new WP_Query($query); if ($queryObject->have_posts()) : while ($queryObject->have_posts()) : $queryObject->the_post(); ?> <li><a <?php if($post->ID == $wp_query->post->ID) echo 'class="chose"'; ?> href="<?php the_permalink() ?>"><?php the_title(); ?></a></li> <?php endwhile; wp_reset_postdata(); endif; ?> </ul>
以上代码中用到了WP_Query来获取文章列表,该对象的使用方法,可以参考WordPress的官方文档:Class Reference/WP Query和Function Reference/query posts。class="chose"用于高亮当前文章的菜单项,css规则你可以自己定义。
五、页面page的获取
WordPress的页面page可以通过wp_list_pages()来列出,不过这个函数输出的HTML都是固定的,如果你想要自定义这些HTML,可以使用get_pages()来获取页面列表,代码示例如下:
<ul id="menu">
$mypages = get_pages();
if(count($mypages) > 0) {
foreach($mypages as $page) {
echo '<li><a href="'.get_page_link($page->ID).'" title="'.$page->post_title.'">'.$page->post_title.'</a></li>';
}
}
else {
echo '<li><a href="#">没有页面</a></li>';
}
</ul>-- 完 --
推荐学习:《WordPress教程》
The above is the detailed content of How to create a theme navigation menu in WordPress (2). For more information, please follow other related articles on the PHP Chinese website!
How to set up version control for WordPress developmentAug 20, 2025 am 09:43 AMThe first step in setting up version control is to install Git and initialize the repository, the second step is to remotely host using platforms such as GitHub for collaboration and backup, the third step is to be careful with WordPress specific files such as themes, plugins, and databases, and the fourth step is to maintain a consistent workflow including branching policies and regular pushes. First install Git locally and initialize the repository through gitinit, create .gitignore files to exclude sensitive or large files; then push the code to a remote platform to take advantage of its collaboration capabilities; then version control of custom themes and plug-ins but avoid tracking third-party content, and manage database and media uploads through tools; finally ensure the development process is smooth and efficient through standardized workflows.
How to register a custom sidebar in WordPressAug 20, 2025 am 07:50 AMToaddacustomsidebarinWordPress,registeritinyourtheme’sfunctions.phpfileanddisplayitinyourtemplates.1.Registerthesidebarbyaddingtheregister_sidebar()functioninsideacustomfunctionhookedtowidgets_init.2.Usetheprovidedcodestructuretodefinethesidebarname,
How to add custom bulk actionsAug 20, 2025 am 07:15 AMTo add custom batch operations in the WordPress background, first use the bulk_actions-{screen_id} filter to add options in the drop-down menu, then implement the operation logic through the handle_bulk_actions-{screen_id} filter, and finally display the prompt information through the admin_notices hook. The specific steps are: 1. Use add_filter() and bulk_actions-{screen_id} to add custom options; 2. Use handle_bulk_actions-{screen_id} to handle the operation logic of the selected items; 3. Use admin_not
How to create a WordPress child themeAug 20, 2025 am 03:08 AMThe key to creating a WordPress sub-theme is to understand its role and structure. 1. The benefits of using child themes include: modification security, saving development time, and easier maintenance and debugging; 2. The basic steps for creating child themes are: create a new folder and create two files: style.css and functions.php, to ensure that the Template field is consistent with the parent theme folder name, and to load the parent theme and child theme style in functions.php; 3. Advanced skills for child themes include: replacing template files, customizing functions and functions, and using additional file structures; 4. Common precautions include: correctly filling in the topic name and template fields, ensuring that the parent theme style is loaded, and confirming compatibility before updating the parent theme.
How to build a custom WordPress registration formAug 19, 2025 pm 06:43 PMTheeasiestwaytocreateacustomWordPressregistrationformisbyusingpluginslikeUserRegistrationorUltimateMember,thoughcustomcodingisanoptionforadvancedusers.①Useapluginforsimplicity,offeringdrag-and-dropformbuilding,conditionallogic,andstylingoptions.②Cust
How to scale WordPress hostingAug 19, 2025 pm 06:39 PMExpanding WordPress hosting solutions requires four aspects: First, upgrade the shared hosting to a VPS or cloud server to improve resource control capabilities and performance; second, introduce page cache, object cache and CDN acceleration to reduce server pressure; third, optimize the database structure, perform data cleaning, splitting and using connection pools; finally, for medium and large sites, load balancing, static resource separation and containerization technologies can be used to achieve multi-site architecture. Each step should be gradually adjusted according to actual traffic and business needs to ensure stable and efficient expansion.
How to troubleshoot internal server errors 500Aug 19, 2025 pm 05:39 PMWhen encountering 500 errors, you should first view the server log 1. View the server log to locate specific error information, such as Apache's error_log, Nginx's logs/error.log and application-level log; 2. Check recent code changes, check for syntax errors, missing dependencies or configuration changes; 3. Verify whether the file permissions and path settings are correct, especially .htaccess and key script permissions; 4. Troubleshoot third-party services or plug-ins, close the test one by one and confirm the availability of external dependencies.
How to use the Admin Bar APIAug 19, 2025 pm 04:58 PMUse AdminBarAPI to extend the WordPress top management bar through the add_node() method to enable quick access to background functions or custom links. 1. When adding main menu items, you need to specify parameters such as id, title, href, and meta, and mount them to the admin_bar_menu hook; 2. When adding submenu, you need to set the parent attribute to the same as the parent node id, and the display order can be controlled by adjusting the hook priority; 3. You can remove the default menu items through remove_node() or remove_menu(); 4. Pay attention to permission control, id uniqueness, multi-language support and debugging skills to improve the compatibility and user experience of plug-ins or themes.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use







