Menu Close

How to get a List of Post Tags in WordPress

default

I was just working on a new premium WordPress theme which I will release sometime next week and as I was creating my site map page template I realized I needed to include a list of all the tags used on the site. After finishing my site map template I figured I would share with you the code required to display a UL list of your WordPress tags, so here it is below…

Creating A UL List With ALL Your Tags

Simply copy and paste the following code wherever you want your tags to appear in your theme files. For further reading see the get_tags codex.

<h2>Tags</h2>
<ul>
    <?php
    $tags = get_tags();
    if ( $tags ) :
        foreach ( $tags as $tag ) : ?>
            <li><a href="<?php echo esc_url( get_tag_link( $tag->term_id ) ); ?>" title="<?php echo esc_attr( $tag->name ); ?>"><?php echo esc_html( $tag->name ); ?></a></li>
        <?php endforeach; ?>
    <?php endif; ?>
</ul>

This code displays a list of all the registered tags on your site. If you want to display a list of tags associated with a specific post then you instead use the function called get_the_tag_list. Example:

echo get_the_tag_list('<p>Tags: ',', ','</p>');

Also, the first snippet uses the get_tags function which is specifically for WordPress tags. However, you can also use the get_terms function which allows you to display terms from any taxonomy in WordPress. For example if your theme has a custom post type which also has tags but they are not the standard post_tag taxonomy you can use the get_terms function to pull an array of all the terms associated with that specific taxonomy.

$tags = get_terms( 'portfolio_tags', array(
    'hide_empty' => false,
) );

Show A Tag Cloud Anywhere In WordPress

Another option is to use the default WordPress tag cloud to show a list of your links and then set the largest and smallest values to the same number so they do not increase in size. You can see my other post on how to manually show a tag cloud in WordPress or see the example snippet below which can be used to show a tagcloud anywhere on the site.

<?php wp_tag_cloud( array(
   'smallest' => 1, // size of least used tag
   'largest'  => 1, // size of most used tag
   'unit'     => 'em', // unit for sizing the tags
   'number'   => 45, // displays at most 45 tags
   'orderby'  => 'name', // order tags alphabetically
   'order'    => 'ASC', // order tags by ascending order
   'taxonomy' => 'post_tag' // you can even make tags for custom taxonomies
) ); ?>

View Source
Posted in WordPress