WordPress自定义文章类型与分类法筛选教程


WordPress自定义文章类型与分类法筛选教程

本教程详细介绍了如何在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 n* 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_n*igation' => _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”文章类型的示例:

AliGenie 天猫精灵开放平台 AliGenie 天猫精灵开放平台

天猫精灵开放平台

AliGenie 天猫精灵开放平台 156 查看详情 AliGenie 天猫精灵开放平台
<?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->h*e_posts() ) :
    while ( $pdf_query->h*e_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 变量到主查询的状态,避免潜在的冲突。

注意事项与最佳实践

  1. 避免使用 query_posts(): query_posts() 会修改主查询,可能导致意想不到的副作用和性能问题。始终使用 new WP_Query() 来创建自定义查询。
  2. 安全性: 如果分类ID或slug来自用户输入(如URL参数),务必使用 absint() 或 sanitize_text_field() 等函数进行安全净化,以防止SQL注入。
  3. 多分类法筛选: 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',
          ),
      )
  4. 性能: 对于大型网站,复杂的 tax_query 可能会影响性能。考虑使用缓存插件或优化数据库查询。
  5. 分页: 确保正确处理分页参数 paged 和 max_num_pages,以便用户可以浏览所有结果。

总结

通过本文的指导,您应该已经掌握了在WordPress中注册自定义文章类型和分类法,并在前端展示筛选选项,以及最重要的是,使用 WP_Query 和 tax_query 参数精确筛选自定义文章类型的方法。遵循这些最佳实践,将帮助您构建功能强大、性能优异且易于维护的WordPress网站。

以上就是WordPress自定义文章类型与分类法筛选教程的详细内容,更多请关注php中文网其它相关文章!


# 是一个  # 朔州抖音seo推广  # 确山关键词排名多少钱  # 唐山品牌推广营销服务商  # 网站制作优化简历的软件  # 裕华区软文网站推广方法  # 网站建设的中心  # 笔趣阁推广网站入口下载  # 传智seo培训学校  # 上海工厂特斯拉网站建设  # 肥西互联网营销推广  # 在这里  # 这一  # 未找到  # 提供一个  # 这是  # php  # 分页  # 多个  # 文档  # 自定义  # 防止sql注入  # sql注入  # win  # pdf  # ai  # wordpress  # go  # ajax  # 前端  # html  # word 


相关栏目: 【 Google疑问12 】 【 Facebook疑问10 】 【 优化推广96088 】 【 技术知识133117 】 【 IDC资讯59369 】 【 网络运营7196 】 【 IT资讯61894


相关推荐: HTML中多图片上传与预览:解决ID冲突的专业指南  Windows Audio服务启动失败怎么办_电脑没声音的终极服务修复法【修复】  mysql镜像配置如何恢复数据_mysql镜像配置数据恢复详细流程  从J*a应用程序中导出MySQL表数据的技术指南  139邮箱登录入口官网 139邮箱登录入口官网网址  申通快件单号查询平台 申通包裹物流动态跟踪  基于 Flink 和 Kafka 实现高效流处理:连续查询与时间窗口  LocoySpider如何批量采集电商商品_LocoySpider电商采集的模板应用  《海底捞》点外卖方法  《KARDS》冬季扩展包“国土阵线”上线!全新“协力”机制改变战场格局  如何定制PrimeNG Sidebar的背景颜色  《跳跳舞蹈》循环播放方法  《下一站江湖2》武器获取方法  视频号视频怎么免费保存到相册?保存到相册需要注意什么?  《爱笔思画x》涂色教程  Win10运行窗口在哪里打开 Win10调出运行命令框快捷键【技巧】  支付宝网页版在线入口 支付宝官网电脑登录入口  Pandas中基于动态偏移量实现DataFrame列值位移的策略  《桃源记2》资源采集攻略  mysql如何管理数据库账户_mysql数据库账户管理技巧  Highcharts雷达图径向轴数值标签实现教程  小红书如何引流到私信?引流到私信有用吗?  《幻兽帕鲁》手游帕鲁捕捉技巧分享  《下一站江湖2》风神腿获取攻略  Win10如何关闭开机锁屏界面_Windows10跳过锁屏直接登录设置  微信客户端如何找回密码_微信客户端忘记密码找回方法  ExcelSCAN与LAMBDA如何创建自定义移动平均函数_SCAN实现任意窗口期移动平均计算  《百果园》充值余额方法  Win10锁屏时间怎么设置 Win10调整自动锁屏时间方法  《下一站江湖2》大雪山加入方法  Chart.js 教程:自定义插件实现图表与图例间距调整  在J*a中如何实现类的继承与方法重用_OOP继承方法重用技巧分享  申通快递物流信息查询 申通快递包裹状态追踪  苹果17 Pro如何启用分屏浏览_iPhone 17 Pro分屏浏览设置步骤  鼠标没反应了怎么办 无线/有线鼠标失灵的解决方法【详解】  DeepSeek超全面指南:入门必看  批改网网页版登录 批改网电脑版学生登录入口  《磁力猫》最好用的磁官网  食品生产用水只要符合国家规定的生活饮用水卫生标准就可以吗  NumPy 高性能技巧:基于多列条件查找最近邻行索引的向量化实现  《东方航空》添加乘机人方法  汽车之家网页版免费登录_汽车之家官网首页直接进入  CSS过渡与滚动滚动事件结合应用_scroll与transition动画  Python对象引用与属性赋值:理解链表中的行为  手机自动关机是怎么回事?如何修复?手机异常关机的原因排查与修复技巧  Eclipse开发J*a快速入门  使用Python和NLTK从文本中高效提取名词的实用教程  Git命令与VS Code UI操作的对应关系解析  如何在mysql中设计餐饮点餐系统_mysql点餐系统项目实战  支付宝登录刷脸不是本人如何解决 

 2025-11-29

了解您产品搜索量及市场趋势,制定营销计划

同行竞争及网站分析保障您的广告效果

点击免费数据支持

提交您的需求,1小时内享受我们的专业解答。

运城市盐湖区信雨科技有限公司


运城市盐湖区信雨科技有限公司

运城市盐湖区信雨科技有限公司是一家深耕海外推广领域十年的专业服务商,作为谷歌推广与Facebook广告全球合作伙伴,聚焦外贸企业出海痛点,以数字化营销为核心,提供一站式海外营销解决方案。公司凭借十年行业沉淀与平台官方资源加持,打破传统外贸获客壁垒,助力企业高效开拓全球市场,成为中小企业出海的可靠合作伙伴。

 8156699

 13765294890

 8156699@qq.com

Notice

We and selected third parties use cookies or similar technologies for technical purposes and, with your consent, for other purposes as specified in the cookie policy.
You can consent to the use of such technologies by closing this notice, by interacting with any link or button outside of this notice or by continuing to browse otherwise.