
本教程详细介绍了如何在wordpress中,通过自定义分类法(taxonomy)对自定义文章类型(custom post type)进行高效筛选。文章将指导您从注册自定义分类法开始,逐步讲解如何在前端展示分类选项,并最终利用`wp_query`结合`tax_query`参数实现精确的文章过滤,确保内容结构清晰、代码示例完整且符合wordpress最佳实践。
在WordPress开发中,自定义文章类型和自定义分类法是构建复杂网站内容结构的基础。当需要根据特定的分类法筛选自定义文章类型时,理解并正确使用WP_Query的tax_query参数至关重要。本文将提供一个全面的指南,帮助开发者实现这一功能。
1. 注册自定义文章类型与分类法
首先,我们需要在functions.php文件或通过插件注册自定义文章类型及其关联的自定义分类法。以下是一个注册名为“pdf”的自定义文章类型及其“pdf_cat”分类法的示例:
// 注册自定义分类法 'pdf_cat'
function register_pdf_taxonomy() {
$labels = array(
'name' => _x( 'PDF 分类', 'taxonomy general name', 'your-text-domain' ),
'singular_name' => _x( 'PDF 分类', 'taxonomy singular name', 'your-text-domain' ),
'search_items' => __( '搜索 PDF 分类', 'your-text-domain' ),
'all_items' => __( '所有 PDF 分类', 'your-text-domain' ),
'parent_item' => __( '父级 PDF 分类', 'your-text-domain' ),
'parent_item_colon' => __( '父级 PDF 分类:', 'your-text-domain' ),
'edit_item' => __( '编辑 PDF 分类', 'your-text-domain' ),
'update_item' => __( '更新 PDF 分类', 'your-text-domain' ),
'add_new_item' => __( '添加新 PDF 分类', 'your-text-domain' ),
'new_item_name' => __( '新 PDF 分类名称', 'your-text-domain' ),
'menu_name' => __( 'PDF 分类', 'your-text-domain' ),
);
$args = array(
'hierarchical' => true, // 设置为层级结构,类似标签
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'pdf-category' ), // 设置分类法URL别名
);
register_taxonomy( 'pdf_cat', array( 'pdf' ), $args ); // 将 'pdf_cat' 分类法关联到 'pdf' 文章类型
}
add_action( 'init', 'register_pdf_taxonomy' );
// 注册自定义文章类型 'pdf'
function register_pdf_post_type() {
$labels = array(
'name' => _x( 'PDF 文档', 'Post type general name', 'your-text-domain' ),
'singular_name' => _x( 'PDF 文档', 'Post type singular name', 'your-text-domain' ),
'menu_name' => _x( 'PDF 文档', 'Admin Menu text', 'your-text-domain' ),
'name_admin_bar' => _x( 'PDF 文档', 'Add New on Toolbar', 'your-text-domain' ),
'add_new' => __( '添加新文档', 'your-text-domain' ),
'add_new_item' => __( '添加新 PDF 文档', 'your-text-domain' ),
'new_item' => __( '新 PDF 文档', 'your-text-domain' ),
'edit_item' => __( '编辑 PDF 文档', 'your-text-domain' ),
'view_item' => __( '查看 PDF 文档', 'your-text-domain' ),
'all_items' => __( '所有 PDF 文档', 'your-text-domain' ),
'search_items' => __( '搜索 PDF 文档', 'your-text-domain' ),
'parent_item_colon' => __( '父级 PDF 文档:', 'your-text-domain' ),
'not_found' => __( '未找到 PDF 文档', 'your-text-domain' ),
'not_found_in_trash' => __( '回收站中未找到 PDF 文档', 'your-text-domain' ),
'featured_image' => _x( 'PDF 封面图', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'your-text-domain' ),
'set_featured_image' => _x( '设置封面图', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'your-text-domain' ),
'remove_featured_image' => _x( '移除封面图', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'your-text-domain' ),
'use_featured_image' => _x( '使用封面图', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'your-text-domain' ),
'archives' => _x( 'PDF 文档存档', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'your-text-domain' ),
'insert_into_item' => _x( '插入到 PDF 文档', 'Overrides the “Insert into post”/“Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'your-text-domain' ),
'uploaded_to_this_item' => _x( '上传到此 PDF 文档', 'Overrides the “Uploaded to this post”/“Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'your-text-domain' ),
'filter_items_list' => _x( '过滤 PDF 文档列表', 'Screen reader text for the filter links on the post type list screen. Added in 4.4', 'your-text-domain' ),
'items_list_navigation' => _x( 'PDF 文档列表导航', 'Screen reader text for the pagination heading on the post type list screen. Added in 4.4', 'your-text-domain' ),
'items_list' => _x( 'PDF 文档列表', 'Screen reader text for the items list heading on the post type list screen. Added in 4.4', 'your-text-domain' ),
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'pdf' ), // 设置文章类型URL别名
'capability_type' => 'post',
'has_archive' => true, // 启用文章类型存档页面
'hierarchical' => false,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
'taxonomies' => array( 'pdf_cat' ), // 关联分类法
);
register_post_type( 'pdf', $args );
}
add_action( 'init', 'register_pdf_post_type' );
2. 在前端展示分类法选项
在前端页面上,您通常会希望提供一个下拉菜单或链接列表,让用户选择特定的分类来筛选文章。以下代码演示了如何获取并显示“pdf_cat”分类法的所有术语(term):
<select onchange="window.location.href=this.value;">
<option value="">所有分类</option>
<?php
$categories = get_terms( array(
'taxonomy' => 'pdf_cat',
'hide_empty' => false, // 显示没有文章的分类
'orderby' => 'name',
'order' => 'ASC',
) );
if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) {
foreach ( $categories as $category ) {
// 获取分类法的存档链接
$term_link = get_term_link( $category );
if ( ! is_wp_error( $term_link ) ) {
echo '<option value="' . esc_url( $term_link ) . '">' . esc_html( $category->name ) . '</option>';
}
}
}
?>
</select>
注意: 上述示例直接生成了分类法的存档链接。当用户点击或选择某个分类时,页面会跳转到该分类的存档页面(例如:yourdomain.com/pdf-category/category-slug/),WordPress会自动处理该页面的文章筛选。如果希望在当前页面通过AJAX或更复杂的逻辑进行筛选,则需要传递分类ID或slug作为参数。
3. 使用 WP_Query 和 tax_query 进行筛选
当用户访问某个自定义分类法的存档页面,或者您需要根据URL参数(例如category_id)在自定义模板中筛选文章时,应使用WP_Query结合tax_query参数。tax_query是处理自定义分类法筛选的正确且推荐方式,因为它允许您精确指定分类法、字段和术语。
以下是如何根据当前分类法的ID筛选“pdf”文章类型的示例:
<?php
// 获取当前分类法的ID。
// 如果在分类法存档页面,可以使用 get_queried_object()
// 如果ID来自URL参数,请确保进行安全验证和净化
$current_term = get_queried_object(); // 在分类法存档页面获取当前分类对象
$catid = 0; // 默认值
if ( $current_term && is_a( $current_term, 'WP_Term' ) && $current_term->taxonomy === 'pdf_cat' ) {
$catid = $current_term->term_id;
}
// 如果是从URL参数获取,例如 ?pdf_cat_id=X
// if ( isset( $_GET['pdf_cat_id'] ) ) {
// $catid = absint( $_GET['pdf_cat_id'] );
// }
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$pdf_args = array(
'post_type' => 'pdf', // 指定自定义文章类型
'paged' => $paged, // 处理分页
'post_status' => 'publish', // 只获取已发布的文章
'posts_per_page' => 15, // 每页显示15篇文章
);
// 只有当 $catid 有效时才添加 tax_query
if ( $catid > 0 ) {
$pdf_args['tax_query'] = array(
array(
'taxonomy' => 'pdf_cat', // 指定分类法名称
'field' => 'term_id', // 指定匹配字段,可以是 'term_id', 'slug', 'name'
'terms' => $catid, // 要匹配的分类法术语ID或slug数组
),
);
}
$pdf_query = new WP_Query( $pdf_args );
if ( $pdf_query->have_posts() ) :
while ( $pdf_query->have_posts() ) : $pdf_query->the_post();
// 在这里显示文章内容
?>
<div class="pdf-item">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<p>分类: <?php the_terms( get_the_ID(), 'pdf_cat', '', ', ', '' ); ?></p>
</div>
<?php
endwhile;
// 分页导航
echo paginate_links( array(
'total' => $pdf_query->max_num_pages,
'current' => $paged,
) );
wp_reset_postdata(); // 重置全局 $post 数据
else :
echo '<p>未找到相关 PDF 文档。</p>';
endif;
?>
代码解析:
- get_queried_object(): 在分类法存档页面(例如 yourdomain.com/pdf-category/some-category-slug/),这个函数会返回当前的 WP_Term 对象,从中可以直接获取 term_id。
- $paged: 用于处理分页,确保在切换页面时能正确显示内容。
- ‘post_type’ => ‘pdf’: 明确指定要查询的自定义文章类型。
-
‘tax_query’: 这是核心部分,它是一个数组,可以包含一个或多个分类法查询数组。
- ‘taxonomy’ => ‘pdf_cat’: 指定要查询的自定义分类法。
- ‘field’ => ‘term_id’: 指定用于匹配的字段。可以是 term_id (推荐), slug, name。
- ‘terms’ => $catid: 要匹配的分类法术语的ID、slug或名称。如果 field 是 term_id,则 terms 应该是一个ID数组或单个ID。
- new WP_Query( $pdf_args ): 创建一个新的 WP_Query 实例,这是在WordPress中进行自定义查询的标准方法。
- wp_reset_postdata(): 在自定义循环结束后,务必调用此函数,以恢复全局 $post 变量到主查询的状态,避免潜在的冲突。
注意事项与最佳实践
- 避免使用 query_posts(): query_posts() 会修改主查询,可能导致意想不到的副作用和性能问题。始终使用 new WP_Query() 来创建自定义查询。
- 安全性: 如果分类ID或slug来自用户输入(如URL参数),务必使用 absint() 或 sanitize_text_field() 等函数进行安全净化,以防止SQL注入。
-
多分类法筛选: tax_query 可以处理更复杂的筛选逻辑,例如:
- 同时满足多个分类法条件: 在 tax_query 数组中添加多个子数组。
-
‘operator’: 可以指定查询操作符,如 ‘AND’, ‘OR’, ‘NOT IN’。
'tax_query' => array( 'relation' => 'AND', // 如果有多个分类法条件,可以指定 AND 或 OR array( 'taxonomy' => 'pdf_cat', 'field' => 'term_id', 'terms' => array( $catid_1, $catid_2 ), // 匹配多个ID中的任意一个 'operator' => 'IN', ), array( 'taxonomy' => 'another_taxonomy', 'field' => 'slug', 'terms' => 'some-slug', ), )登录后复制
- 性能: 对于大型网站,复杂的 tax_query 可能会影响性能。考虑使用缓存插件或优化数据库查询。
- 分页: 确保正确处理分页参数 paged 和 max_num_pages,以便用户可以浏览所有结果。
总结
通过本文的指导,您应该已经掌握了在WordPress中注册自定义文章类型和分类法,并在前端展示筛选选项,以及最重要的是,使用 WP_Query 和 tax_query 参数精确筛选自定义文章类型的方法。遵循这些最佳实践,将帮助您构建功能强大、性能优异且易于维护的WordPress网站。
以上就是WordPress自定义文章类型与分类法筛选教程的详细内容,更多请关注php中文网其它相关文章!


