【问题标题】:Wordpress - How can I get_categories from additional custom post?Wordpress - 我如何从其他自定义帖子中获取_categories?
【发布时间】:2022-01-19 05:41:30
【问题描述】:

我的目标是从我在functions.php 中注册的附加自定义帖子中获取类别。如何获取它的类别并在我的页面上回显它?到目前为止,这是我的代码: 来自页面:

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

来自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
                  $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


    【解决方案1】:

    wordpress 中自定义帖子类型的类别使用分类功能。在这种情况下,您可以使用get_terms 获取“类别”。

    例子

    $categories = get_terms([
        'taxonomy' => 'pdf_cat',
        'hide_empty' => false,
    ]);
    

    【讨论】:

    • 但是当我点击特定类别名称时如何回显它?我发布了我的新代码
    • @maru 您只需回显对象,$categories 只是一个数组,因此只需使用 for-each 对其进行迭代,然后回显分类对象的属性
    • 嗨@infamoustrey 希望你能帮我解决我的问题stackoverflow.com/questions/70417765/…
    猜你喜欢
    • 1970-01-01
    • 2018-08-02
    • 2016-10-28
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    相关资源
    最近更新 更多