Table of Contents
1. Use get_terms() to get the category list
2. Use the method of reading the database to obtain the classification list
3. How to get the id of the current category
四、子导航的制作
五、页面page的获取
Home CMS Tutorial WordPress How to create a theme navigation menu in WordPress (2)

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

Feb 23, 2023 pm 07:44 PM
php wordpress

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 ) ?>
Copy after login

$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>
Copy after login

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>
Copy after login

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;);
}
Copy after login

Get the first category of the article on the article page:

$cats = get_the_category();
if($cats)
    $cat_id = $cats[0]->cat_ID;
Copy after login

四、子导航的制作

上面我们讲解了如何获取当前分类的id,下面我们来讲讲如何制作子导航。首先,我们来制作一个当前分类下子分类的子导航,这里用到wp_list_categories()来列出子分类,当然你可以用我前面介绍的两种方法来获取分类。:

<ul>
<?php
// 这里我们用到上面获取到的$cat_id,获取该分类下的所有子分类
wp_list_categories(&#39;orderby=name&hide_empty=0&child_of=&#39; . $cat_id);
?> 
</ul>
Copy after login

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

<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>
Copy after login

以上代码中用到了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>
Copy after login

-- 完 --

推荐学习:《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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

WordPress site file access is restricted: Why is my .txt file not accessible through domain name? WordPress site file access is restricted: Why is my .txt file not accessible through domain name? Apr 01, 2025 pm 03:00 PM

Wordpress site file access is restricted: troubleshooting the reason why .txt file cannot be accessed recently. Some users encountered a problem when configuring the mini program business domain name: �...

See all articles