【问题标题】:Wordpress: Display Custom Post Type Alphabetized by Custom Taxonomy?Wordpress:按自定义分类按字母顺序显示自定义帖子类型?
【发布时间】:2025-12-28 12:20:08
【问题描述】:

我创建了一个名为“教育”的自定义帖子类型。使用这种自定义帖子类型,我制作了一个名为“Years”的自定义分类法。假设我要以这种格式为此自定义帖子类型添加大约 10 个帖子:

title of custom post type (Education), Custom Taxonomy Name (Year)

如何在我的页面上按顺序显示帖子的标题和分类名称?

(像这样)

Vimy College      2014
Albatross         2013
Some College      2011
Another College   2010
...
...

到目前为止,这是我页面的代码:

<?php /* Template Name: Education Page */
get_header(); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<div>
<?php
    // The args here might be constructed wrong
    $args = array( 'post_type' => 'education', 
                   'terms' => 'years', 
                   'orderby' => 'terms', 
                   'order' => 'ASC');

    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();

        echo '<h3>';
        the_title();
        echo '</h3>';

        // I don't know what else to put here to display the associated taxonomy name
        // (and in sequential order)

    endwhile;
?>

</div>

<?php endwhile; endif; ?>

所以澄清一下,第一个 have_posts() 循环只是回显实际页面,内部循环应该生成上述格式以列出帖子标题,但按自定义分类名称排序(在这种情况下,数字)。

【问题讨论】:

    标签: php wordpress custom-post-type custom-taxonomy


    【解决方案1】:

    这应该可以解决问题

    <?php
    $terms = get_terms('year', array('order' => 'DESC'));
    foreach($terms as $term) {
        $posts = get_posts(array(
            'post_type' => 'education',
            'tax_query' => array(
                array(
                    'taxonomy' => 'year',
                     'field' => 'slug',
                     'terms' => $term->slug
                )
            ),
            'numberposts' => -1
        ));
        foreach($posts as $post) {
            the_title();
            echo '<br>';
            $term_list = wp_get_post_terms($post->ID, 'year', array("fields" => "names"));
            foreach ($term_list as $t) {
                echo $t;
            }
            echo '<br><br>';
        }
    } 
    ?>
    

    【讨论】:

      【解决方案2】:

      如果您想在帖子列表中显示您的分类,请检查以下代码。

      <?php 
      $terms = get_terms('years');
      foreach ($terms as $term) {
      $wpq = array ('taxonomy'=>'years','term'=>$term->slug);
      $myquery = new WP_Query ($wpq);
      $article_count = $myquery->post_count;
      ?>
      <?php echo $term->name.':';
      if ($article_count) {
      while ($myquery->have_posts()) : $myquery->the_post();
      $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
      ?>
      <a href="<?php the_permalink(); ?>">
      <img alt="<?php echo get_the_title(); ?>" src="<?php echo $feat_image;?>"/> 
      </a>
      <a href="<?php the_permalink(); ?>"><b><?php echo get_the_title(); ?></b></a>
      <?php  endwhile;
      wp_reset_postdata();                
      } ?>
      
      <?php } ?>
      

      【讨论】: