0
votes

I've made a custom post type called "Education". With this custom post type I made a custom taxonomy by the name of "Years". Say I were to add roughly around 10 posts for this custom post type in this format:

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

How would I display on my page the title of the post and it's taxonomy name in sequential order?

(like so)

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

Here's the code for my page so far:

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

So to clarify, the first have_posts() loop just echoes out the actual page, and the inner loop is supposed to generate the format mentioned above for listing the post titles but ordered by the custom taxonomy name (in this case, numerical).

2

2 Answers

1
votes

This should do the trick

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

If you want show your taxnomy with your post listing Please check below code.

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