Wordpress:显示自定义 Post 类型按自定义分类按字母顺序排列?

Wordpress: Display Custom Post Type Alphabetized by Custom Taxonomy?

我创建了一个名为 "Education" 的自定义 post 类型。使用此自定义 post 类型,我创建了一个名为 "Years" 的自定义分类法。假设我要为此自定义 post 类型添加大约 10 posts,格式如下:

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

如何在我的页面上按顺序显示 post 的标题及其分类名称?

(像这样)

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() 循环只是回显实际页面,内部循环应该生成上面提到的用于列出 post 标题但按自定义排序的格式分类法名称(在本例中为数字)。

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

<?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 } ?>

这应该可以解决问题

<?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>';
    }
} 
?>