如何将每个类别的最后发布缩略图作为类别缩略图

时间:2016-01-20 18:32:32

标签: php wordpress

我正在环顾谷歌和这里,但没有发现这一点。

<div class="thumbBlock">
<?php foreach (get_categories() as $cat) : ?>
<div class="thumbInside">
<a href="<?php echo get_category_link($cat->term_id); ?>" title="<?php echo $cat->name; ?>" />
<img src="POST_THUMBNAIL HERE FOR EACH CATEGORY" alt="<?php echo $cat->name; ?>" />
</a>
<p><a href="<?php echo get_category_link($cat->term_id); ?>" title="<?php the_title(); ?>"><?php echo $cat->cat_name; ?></a></p>
</div>
 <?php endforeach; ?>
</div>

正如你所见,我想在自定义模板中列出类别,但在帖子缩略图中我想抓住每个类别的最后一个帖子拇指是否可能?

1 个答案:

答案 0 :(得分:0)

我认为你会发现the_terms和get_the_terms是更好的功能

    $terms = get_terms( 'my_taxonomy' );
     if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
         echo '<ul>';
         foreach ( $terms as $term ) {
           echo '<li>' . $term->name . '</li>';

            /* use the term id to find matching posts in this taxonomy */
    $args = array (
        'showposts' => 1,
        'orderby' => 'date',
        'order' => 'DESC',
        'tax_query' => array(
            array(
                'taxonomy' => 'my_taxonomy',
                'field'    => 'term_id',
                'terms'    => $term->term_id,
            ),
        ),
        );

    $new_query = new WP_Query( $args );
    if ( $new_query->have_posts() ) {

        while ( $new_query->have_posts() ) {
            $new_query->the_post(); 
            $post_id = get_the_ID();
            echo '<li>';
            echo get_the_post_thumbnail( $post_id, 'thumbnail' );
            echo '</li>';
        } // end while

    } else {
        // no posts found
    }
    /* Restore original Post Data */
    wp_reset_postdata();


         }
         echo '</ul>';
     }

这尚未经过测试,但应该非常接近。