代码之家  ›  专栏  ›  技术社区  ›  Darkkz

从自定义帖子类型获取类别

  •  1
  • Darkkz  · 技术社区  · 9 年前

    我买了一个Wordpress主题,希望在一些代码定制之后,它能达到我想要的效果。

    现在,我有了一个名为“Portofolio”的自定义帖子类型。正如您在下图中看到的,它有portofolio条目(所有portofoli条目)和前面提到的portoflio条目的类别。

    enter image description here

    我试图实现的是在自定义模板页面上列出portofolio的所有类别。到目前为止,我有这个代码,但它所做的只是获取portofolio的条目,而不是类别。

        <?php
    //$args = array('post_type' => 'tm_portfolio');
    $term_ids = get_terms( 'tm_portfolio_category', ['fields' => 'ids'] );
    $args = [
        'tax_query' => [
            [
                'taxonomy' => 'tm_portfolio_category',
                'terms' => $term_ids
            ]
        ]
    ];
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo 'List of categories';
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>
    

    正如您在代码中看到的,作为第一行,我尝试从自定义post类型获取,但得到了相同的结果。

    我在添加一个类别的同时,通过检查管理面板中的链接,找到了帖子类型/分类的名称/slug(查看下图)。 enter image description here

    1 回复  |  直到 9 年前
        1
  •  1
  •   Richard Miles    9 年前

    我没有仔细研究代码,但从一开始就可以看出这一行是不对的。

    $term_ids = get_terms( 'tm_portfolio_category', ['fields' => 'ids'] );
    

    它应该是“id”

    例如

    $term_ids = get_terms( 'tm_portfolio_category', ['fields' => 'id'] );
    

    编辑

    对不起,我的错,

    你可以试试这种方法

    $term_ids = get_terms( 'tm_portfolio_category', ['fields' => 'ids'] );
    
    $posts = query_posts( array(
        'post_type' => 'tm_portfolio',
        'tax_query' => array(
            array(
                'taxonomy' => 'tm_portfolio_category',
                'terms'    => $term_ids,
                )
            )
        ));
    
    foreach ($posts as $post) {
       echo 'List of categories';
       ?>
       <p><a href="<?php echo get_permalink($post->ID); ?>" title="Permanent Link to <?php echo the_title_attribute(array('post'=>$post->ID)); ?>">
       <?php echo get_the_title($post->ID); ?>
        </a></p>
       <?php
    }
    wp_reset_query();
    

    为了灵活性,我不建议在这种情况下使用原生WordPress循环。

    我已经在我这边测试过了,它似乎在起作用。当您使用get_terms时,可能需要重新定位返回的内容,因为返回的数组可能会以与接收查询参数不同的方式进行索引。

    编辑

    对不起,我觉得我一直在错过最初的问题。

    $terms = get_terms( 'tm_portfolio_category' );
    

    会给你一个术语表。

    foreach ($terms as $term) {
        ?>
        List of categories
        <p>
            <a href="<?php echo $term->slug; ?>" title="Permanent Link to <?php echo $term->name ?>" ><?php echo $term->name ?></a>
        </p>
        <?php 
    }
    
    ?>
    

    下面应该会给出所需的结果,而无需创建另一个查询。