List categories by terms of the second taxonomy: Taxonomy Archives

WBOY
Release: 2023-09-01 11:06:01
Original
669 people have browsed it

按第二个分类法的术语列出分类目录:Taxonomy Archives

If your site uses multiple taxonomies to classify information, it can be helpful to split the posts in the taxonomy archive based on the terms of the second taxonomy.

In this tutorial, I will show you how to create a taxonomy archive to achieve this purpose.

If you've ever used any relational databases, you know that one of their great features is that you can view data according to multiple taxonomies. For example, if you have a client database, you can easily see which clients hire you for different categories of projects, and then sort further by seeing which web design clients are located in a given location, for example.

When I first started using WordPress, I was frustrated that you couldn't do this easily - at least you couldn't do it with an out-of-the-box WordPress installation running the default theme.

However, data can be classified through a variety of taxonomies. in this tutorial. I'll show you how to create a category page that lists the posts in that category, sorted by terms that also apply to another category in which they exist.

I will then create a second category archive for the second category that lists its posts in the order of the terms of the first category (trust me - it will make more sense when you see it happen! )

<h2>What do you need

To complete this tutorial you will need:

  • Development installation of WordPress
  • Code Editor
<h2>1. Create topic

In this tutorial, I will create a 24 child theme using two new template files, a stylesheet, and a function file. If you use your own theme, simply copy the code from my functions file into your theme's functions file, then add the template file adjusted to reflect your theme's markup.

To create my theme, I create a file called style.css in the empty theme folder and populate it with the following content:

/*
Theme Name:     WPTutsPlus Create a Taxonomy Archive to List Posts by a Second Taxonomy's Terms
Theme URI:      https://rachelmccollin.co.uk/wptutsplus-taxonomy-archive-list-by-second-taxonomy/
Description:    Theme to support WPTutsPlus tutorial on creating a custom taxonomy archive. Child theme for the Twenty Fourteen theme.
Author:         Rachel McCollin
Author URI:     http://rachelmccollin.co.uk/
Template:       twentyfourteen
Version:        1.0
*/

@import url("../twentyfourteen/style.css");
Copy after login

This will create my child theme.

<h2>2. Register post types and taxonomies

In this tutorial I will be using the same 'animals' post type and 'animal_cat' taxonomy custom post type template that I used in the create tutorial. I will also add a second taxonomy called 'habitat'.

To do this, I create a new file called functions.php. First, I add functions to register my post type:

<?php
// register a custom post type called 'animals'
function wptp_create_post_type() {
    $labels = array( 
		'name' => __( 'Animals' ),
		'singular_name' => __( 'animal' ),
		'add_new' => __( 'New animal' ),
		'add_new_item' => __( 'Add New animal' ),
		'edit_item' => __( 'Edit animal' ),
		'new_item' => __( 'New animal' ),
		'view_item' => __( 'View animal' ),
		'search_items' => __( 'Search animals' ),
		'not_found' =>  __( 'No animals Found' ),
		'not_found_in_trash' => __( 'No animals found in Trash' ),
	);
	$args = array(
		'labels' => $labels,
		'has_archive' => true,
		'public' => true,
		'hierarchical' => false,
		'supports' => array(
			'title', 
			'editor', 
			'excerpt', 
			'custom-fields', 
			'thumbnail',
			'page-attributes'
		),
		'taxonomies' => array( 'post_tag', 'category'), 
	);
	register_post_type( 'animal', $args );
} 
add_action( 'init', 'wptp_create_post_type' );
?>
Copy after login

Then I register my two taxonomies in a function:

<?php
// register taxonomies
function wptp_register_taxonomies() {
    
	// register a taxonomy called 'Animal Family'
	register_taxonomy( 'animal_cat', 'animal',
		array(
			'labels' => array(
				'name'              => 'Animal Families',
				'singular_name'     => 'Animal Family',
				'search_items'      => 'Search Animal Families',
				'all_items'         => 'All Animal Families',
				'edit_item'         => 'Edit Animal Families',
				'update_item'       => 'Update Animal Family',
				'add_new_item'      => 'Add New Animal Family',
				'new_item_name'     => 'New Animal Family Name',
				'menu_name'         => 'Animal Family',
			),
			'hierarchical' => true,
			'sort' => true,
			'args' => array( 'orderby' => 'term_order' ),
			'rewrite' => array( 'slug' => 'animal-family' ),
			'show_admin_column' => true
		)
	);
	
	// register a taxonomy called 'Habitat'
	register_taxonomy( 'habitat', 'animal',
		array(
			'labels' => array(
				'name'              => 'Habitats',
				'singular_name'     => 'Habitat',
				'search_items'      => 'Search Habitats',
				'all_items'         => 'All Habitats',
				'edit_item'         => 'Edit Habitat',
				'update_item'       => 'Update Habitat',
				'add_new_item'      => 'Add New Habitat',
				'new_item_name'     => 'New Habitat Name',
				'menu_name'         => 'Habitat',
			),
			'hierarchical' => true,
			'sort' => true,
			'args' => array( 'orderby' => 'term_order' ),
			'show_admin_column' => true
		)
	);
}
add_action( 'init', 'wptp_register_taxonomies' );
?>
Copy after login

This will create the 'animal' post type and the two taxonomies that apply to it. Note that I used 'show_admin_column' to make it easier when managing my posts.

After adding some data and classifying the animals according to my taxonomy, I can now view my data in the WordPress dashboard as shown below.

Note: My classification of the animals I use is not very scientific - please do not comment on my understanding of habitats or families!

按第二个分类法的术语列出分类目录:Taxonomy Archives

<h2>3. Create the first classification template file

The next step is to create a template file for the 'animal_cat' category archive. Create a file in your theme folder and name it taxonomy-animal_cat.php. Now add the wrapper code from your theme (I have copied this code from my parent theme, if you use your own theme your code will be different):

<?php
/*
WpTutsPlus tutorial for creating archive to display posts by mutiple taxonomy terms
Archive template for animal_cat taxonomy
*/
?>

<?php get_header(); ?>

    <div id="main-content" class="main-content">

	<div id="primary" class="content-area">
		<div id="content" class="site-content" role="main">

			
		</div><!-- #content -->
	</div><!-- #primary -->
	<?php get_sidebar( 'content' ); ?>
</div><!-- #main-content -->

<?php
get_sidebar();
get_footer();
Copy after login

Now you need to add some data to this template file.

Identify the term of the current query

The archive template will use WP_Query to create a custom query for each term. One of the objects of the query will be the currently displayed taxonomy term, so you need to identify it and store it as a variable.

Below the line get_header(), add:

<?php
// get the currently queried taxonomy term, for use later in the template file
$animalcat = get_queried_object();
?>
Copy after login

You can use the $animalcat variable later.

Output page title

The archive currently does not have a main title, so you need to add one using the variable you just defined.

After opening the <div id="content"> tag, add the following:

<header class="archive-header">
    <h1 class="archive-title">
		<?php echo $animalcat->name; ?>
	</h1>
</header><!-- .archive-header -->
Copy after login

Get the terms of the second category

Next, you need to get the list of terms for the second category. Insert the following below the code you just added:

<?php //start by fetching the terms for the animal_cat taxonomy
$terms = get_terms( 'habitat', array(
    'hide_empty' => 0
) );
?>
Copy after login

This will get a list of all terms and store them in an array. By using 'hide_empty' you can avoid showing any empty terms - but as you will soon see, this will only prevent queries for terms that have no posts at all, not those that have no posts for the current query classification terms.

创建循环

现在创建一个将为每个术语运行的循环:

<?php
// now run a query for each animal family
foreach ( $terms as $term ) {

    // Define the query
	$args = array(
		'post_type' => 'animal',
		'animal_cat' => $animalcat->slug,
		'habitat' => $term->slug
	);
	$query = new WP_Query( $args );
			
	// output the term name in a heading tag				
	echo'<h2>' . $term->name . ' habitat</h2>';
	
	// output the post titles in a list
	echo '<ul>';
	
		// Start the Loop
		while ( $query->have_posts() ) : $query->the_post(); ?>

		<li class="animal-listing" id="post-<?php the_ID(); ?>">
			<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
		</li>
		
		<?php endwhile;
	
	echo '</ul>';
	
	// use reset postdata to restore orginal query
	wp_reset_postdata();

} ?>
Copy after login

对此的一些说明:

  • 为每个术语定义一个新查询。
  • 查询的参数包括第二个分类中的术语 ($term) 和当前正在查询的术语 ($animalcat)。
  • 如果您的分类法仅适用于一种帖子类型,您可以省略 'post_type' 参数,但我更愿意包含它以防万一。
  • $term 变量用于使用 $term->name 输出每个部分的标题。

现在保存您的模板文件并查看您的动物家族术语之一的分类存档:

按第二个分类法的术语列出分类目录:Taxonomy Archives

为每个查询添加帖子检查

目前,如您所见,模板正在输出空列表。通过检查每个查询是否有帖子可以轻松解决此问题。

在循环中包含以下内容:

if ( $query->have_posts() ) {

}
Copy after login

你的循环现在看起来像这样:

if ( $query->have_posts() ) {
    
	// output the term name in a heading tag				
	echo'<h2>' . $term->name . ' habitat</h2>';
	
	// output the post titles in a list
	echo '<ul>';
	
		// Start the Loop
		while ( $query->have_posts() ) : $query->the_post(); ?>

		<li class="animal-listing" id="post-<?php the_ID(); ?>">
			<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
		</li>
		
		<?php endwhile;
	
	echo '</ul>';
}
Copy after login

如果查询没有任何帖子,这会阻止 WordPress 运行循环,从而删除那些空标题。现在我的存档页面如下所示:

按第二个分类法的术语列出分类目录:Taxonomy Archives

好多了!

<h2>为第二个分类创建模板文件

最后一步是为第二个分类的档案创建模板文件。

复制您的第一个模板文件并将其重命名为 taxonomy-habitat.php。编辑它以使术语正确。我需要对文件进行的编辑是:

  • 调整文件顶部的注释,使其准确
  • $animalcat 变量的名称更改为 $habitat (您可以通过为该变量指定一个更通用的名称来避免此问题 - 但不要将其称为 $term 因为您在其他地方使用它)
  • 编辑 <h1> 标题,以便它使用 $habitat 变量来输出当前查询术语的名称(我还在此处添加了一些解释性文本)这是可选的)
  • 更改 get_terms() 函数的第一个参数,使其使用 animal_cat 术语,而不是 habitat 术语。
  • 编辑查询参数,本质上是交换 'animal_cat''habitat' 的值。
  • 编辑循环中的 <h2> 内容以引用家庭而不是栖息地。

这意味着我的新模板文件如下所示:

<?php
/*
WpTutsPlus tutorial for creating archive to display posts by mutiple taxonomy terms
Archive template for habitat taxonomy
*/
?>

<?php get_header(); ?>

<?php
// get the currently queried taxonomy term, for use later in the template file
$habitat = get_queried_object();
?>

    <div id="main-content" class="main-content">

	<div id="primary" class="content-area">
		<div id="content" class="site-content" role="main">

<header class="archive-header">
	<h1 class="archive-title">
		Habitat - <?php echo $habitat->name; ?>
	</h1>
</header><!-- .archive-header -->

<?php //start by fetching the terms for the animal_cat taxonomy
$terms = get_terms( 'animal_cat', array(
	'hide_empty' => 0
) );
?>

<?php
// now run a query for each animal family
foreach( $terms as $term ) {

	// Define the query
	$args = array(
		'post_type' => 'animal',
		'animal_cat' => $term->slug,
		'habitat' => $habitat->slug
	);
	$query = new WP_Query( $args );
	
	if( $query->have_posts() ) {
		
		// output the term name in a heading tag				
		echo'<h2>' . $term->name . ' family</h2>';
		
		// output the post titles in a list
		echo '<ul>';
		
			// Start the Loop
			while ( $query->have_posts() ) : $query->the_post(); ?>
	
			<li class="animal-listing" id="post-<?php the_ID(); ?>">
				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
			</li>
			
			<?php endwhile;
		
		echo '</ul>';
	}
			
	
	
	// use reset postdata to restore orginal query
	wp_reset_postdata();

} ?>
			
		</div><!-- #content -->
	</div><!-- #primary -->
	<?php get_sidebar( 'content' ); ?>
</div><!-- #main-content -->

<?php
get_sidebar();
get_footer();
Copy after login

进行这些更改后,保存新模板文件并检查您的存档之一:

按第二个分类法的术语列出分类目录:Taxonomy Archives

您现在拥有第二个分类的页面,其工作方式与第一个分类相同。

<h2>摘要

在本教程中,您学习了一种使用多种分类法显示数据的方法。您可以通过以下两种方式之一使用第三种分类法来进一步实现这一点:

  1. 重复获取术语、定义查询并为第二个术语之后的第三个术语运行循环的过程,以便您拥有两个单独的列表。
  2. 使用所有三个术语合并您的数据,方法是使用每个 $term 变量,其方式与 $habitat$animalcat 变量类似并在现有的 foreach() 语句中添加额外的 foreach() 语句。然后,您需要考虑如何使用列表或网格来布局结果数据。

为什么不尝试一下呢?

The above is the detailed content of List categories by terms of the second taxonomy: Taxonomy Archives. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!