如何按标签分组文章?

时间:2011-12-27 10:17:57

标签: wordpress

我需要按照以下标签对文章进行分组:

TAG1
Article 1
Article 2
Article 5
TAG2
Article 3
Article 4
TAG3
Article 6
Article 7
Article 8

我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

这应该有效:

<?php
    $args = array(
        'orderby'       => 'name',
        'order'         => 'ASC',
        'hide_empty'    => 1,
        'taxonomy'      => 'post_tag', //change this to any taxonomy
    );
    foreach (get_categories($args) as $tax) :
        $args = array(
            'post_type'         => 'post', //change to your post_type
            'posts_per_page'    => -1,
            'orderby'           => 'title',
            'orderby'           => 'ASC',
            'tax_query' => array(
                array(
                    'taxonomy'  => 'post_tag', //change this to any taxonomy
                    'field'     => 'slug',
                    'terms'     => $tax->slug
                )
            )
        );
        if (get_posts($args)) :
    ?>
        <h2><?php echo $tax->name; ?></h2>
        <ul>
            <?php foreach(get_posts($args) as $p) : ?>
                <li><a href="<?php echo get_permalink($p); ?>"><?php echo $p->post_title; ?></a></li>
            <?php endforeach; ?>
        </ul>
    <?php 
        endif;
    endforeach; 
?>