是否按每个类别显示最后一篇帖子?

时间:2020-01-05 作者:Milosh N.

如何按类别显示最后一篇文章?

重点是显示页面上所有类别的最后一篇文章,我需要像往常一样将它们显示在前面<ul><li> 列表

有什么想法吗?

谢谢

1 个回复
SO网友:Daniel Gross

Try this

<?php
$post_type = "post";
$taxonomy = "category";
$terms = get_terms(
    array(
        \'taxonomy\' => $taxonomy,
        \'hide_empty\' => 0,
        \'hierarchical\'=> 1,
    )
);

echo \'<ul>\';

foreach($terms as $term):

    $term_id = $term->term_id;
    $term_name = $term->name;

    $query = array(
        \'post_type\' => $post_type, 
        \'post_status\' => \'publish\',
        \'posts_per_page\' => 1,
    );
    $query[\'tax_query\'] = array(
        array(
            \'taxonomy\' => $taxonomy,
            \'terms\' => $term_id
        )
    );
    $posts = new WP_Query($query);

    while($posts->have_posts()):
        $posts->the_post();
        $permalink = get_permalink($post->ID);
        $post_title = $post->post_title;
        $get_term_link = get_term_link($term_id);
    ?>
        <li>
        <!--<?php //echo the_terms( $post->ID, $taxonomy, \'Term: \', \' &raquo; \' );// with link?> &raquo;-->
        <!-- Term(s): <?php //echo join(\', \',wp_get_post_terms($post->ID, $taxonomy, array("fields" => "names")));// without link?> &raquo;  -->
        <?php echo \'<a href="\'.$get_term_link.\'">\'.$term_name.\'</a>\';?>  &raquo; 
        Last Post: <a href="<?php echo $permalink;?>"><?php echo $post_title;?></a>
        </li>
    <?php
    endwhile;

endforeach;

echo \'</ul>\';       
?>

相关推荐

Loop through array of pages

我正在尝试递归地获取页面的所有子级(无限深度),我正在使用下面的函数,from this solution:function get_all_subpages($page, $args = \'\', $output = OBJECT) { if (! is_numeric($page)) $page = 0; $default_args = array( \'post_type\' => \'page\',&