search
HomeCMS TutorialWordPressHow to create a theme navigation menu in WordPress (2)

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!

How to create a theme navigation menu in WordPress (2)

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

  • ..
  • ..
of all article categories will be displayed. Of course, we can Think of it as a menu:
<ul id="menu">		
<?php
	// 获取分类
	$terms = get_terms(&#39;category&#39;, &#39;orderby=name&hide_empty=0&#39; );

	// 获取到的分类数量
	$count = count($terms);
	if($count > 0){
		// 循环输出所有分类信息
		foreach ($terms as $term) {
			echo &#39;<li><a href="&#39;.get_term_link($term, $term->slug).&#39;" title="&#39;.$term->name.&#39;">&#39;.$term->name.&#39;</a></li>&#39;;
		}
 	}
?>		
</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 = &#39;category&#39;");
							
	if($cats) {
		foreach($cats as $cat) {
			echo &#39;<li><a href="&#39;.get_category_link($cat->term_id).&#39;" title="&#39;.$cat->name.&#39;">&#39;.$cat->name.&#39;</a></li>&#39;;
		}
 	}
?>		
</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(&#39;cat&#39;);
}

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(&#39;orderby=name&hide_empty=0&child_of=&#39; . $cat_id);
?> 
</ul>

     如果你的网站规模比较小,一个分类下的文章也不多,那么你可以在子导航中列出这个分类下的所有文章:

<ul>
	<?php
		global $wp_query;

		$query = array ( &#39;cat&#39; => $cat_id, &#39;orderby&#39; => title, &#39;order&#39;=> 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 &#39;class="chose"&#39;; ?> href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
	<?php endwhile; wp_reset_postdata(); endif; ?>
</ul>

     以上代码中用到了WP_Query来获取文章列表,该对象的使用方法,可以参考WordPress的官方文档:Class Reference/WP QueryFunction 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 &#39;<li><a href="&#39;.get_page_link($page->ID).&#39;" title="&#39;.$page->post_title.&#39;">&#39;.$page->post_title.&#39;</a></li>&#39;;
    }
}
else {
    echo &#39;<li><a href="#">没有页面</a></li>&#39;;
}
</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!

Statement
This article is reproduced at:露兜即刻. If there is any infringement, please contact admin@php.cn delete
Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

How customizable is WordPress, really?How customizable is WordPress, really?May 11, 2025 am 12:11 AM

WordPress is very customized, providing a wide range of flexibility and customizability. 1) Through the theme and plug-in ecosystem, 2) use RESTAPI for front-end development, 3) In-depth code level modifications, users can achieve a highly personalized experience. However, customization requires mastering technologies such as PHP, JavaScript, CSS, etc., and pay attention to performance optimization and plug-in selection to avoid potential problems.

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 Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development 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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment