【问题标题】:Wordpress - how to filter the added custom post through its taxonomy?Wordpress - 如何通过其分类过滤添加的自定义帖子?
【发布时间】:2022-01-19 08:08:23
【问题描述】:

我在我的functions.php 中添加了一个新的自定义帖子,如何通过其分类对现有帖子进行排序?目标是在点击特定类别时过滤现有帖子。下面是示例代码:

在functions.php中添加了自定义帖子:

  $args = array(
   'label' => 'category',
   'public' => true,
   'show_ui' => true,
   'show_in_nav_menus' => true,
   'show_admin_column' => true,
   'hierarchical' => true,
   'query_var' => true
  );
   register_taxonomy('pdf_cat','pdf',$args);

在页面上 - 获取分类并将其作为我的类别选项:

<?php
  $args = array(
  'post_type' => 'pdf',
  'orderby' => 'slug',
  'order' => 'ASC',
  'parent' => 0,
  'hide_empty' => false
   );
  $categories = get_terms([
    'taxonomy' => 'pdf_cat',
    'hide_empty' => false,
     ]);
    foreach( $categories as $category ){
      echo '<option><a class="ctg" href="'. get_category_link( $category->term_id ) .' ">' . $category->name . '</a></option>';
     }
   ?>   

点击特定类别时通过其分类过滤现有帖子:

            <?php
              $cat = get_the_category();
              $cat = $cat[0]; 
              $catname = get_cat_name($cat->term_id); 
              $catid = get_cat_ID($catname);  
            ?>
              
            <?php
                  $paged = get_query_var('paged', 1);
                  $args = array(  
                      'post_type' => 'pdf',
                      'paged' => $paged,
                      'post_type' => 'post',
                      'cat' => $catid,
                  );
                  $query = new WP_Query($args);         
         
              global $query_string; 
              query_posts( $query_string . "&posts_per_page=15&paged=".$paged );
              while ( have_posts() ) : the_post()
            ?>

【问题讨论】:

    标签: php html wordpress categories custom-taxonomy


    【解决方案1】:

    你需要使用tax_query

    $pdf_args = array(
        'post_type'   => 'pdf',
        'paged'       => $paged,
        'post_status' => 'publish',
        'tax_query'   => array(
            array(
                'taxonomy' => 'pdf_cat',
                'field'    => 'term_id',
                'terms'    => $catid,
            ),
        ),
    )
    
    $pdf_data = new WP_Query( $pdf_args );  
    

    了解更多详情here

    【讨论】:

    • 这段代码应该放在哪里?
    • 我在如何将术语 id 变成每个类别的永久链接时遇到了麻烦
    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多