0

I'm building a site glossary and trying to display only tags with descriptions. Is there a way to determine if the description is available and only display the tag when it is?

Here is where I am so far.

    $tags = get_tags();
    if (tag_description($tag->term_id)) {
        if ($tags) {
            foreach ($tags as $tag) {
                echo '<dt><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'</a></dt><dd>' . tag_description($tag->term_id) . '</dd>';
            }
        }
    }
4

The object returned by get_tags() should have a description property, so you don't need to try to get it again. Just check to be sure $tags->description isn't empty. You should probably also reorganize so that you don't do anything at all unless if($tags). Thus:

// Get ALL the tags!
$tags = get_tags( array( 'hide_empty' => false ) );
if ($tags) {
  foreach ($tags as $tag) {
    if ($tag->description) {
      echo '<dt><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'</a></dt><dd>' . $tag->description . '</dd>';
    }
  }
}
  • It's odd I'm finding that it's not updating the list when I add more. Does it only show tag that are attached to posts? If so, how would I display all tags? – Zach Shallbetter Aug 31 '11 at 17:14
  • Ah yeah, get_tags() excludes empty ones by default. I've updated my answer to get all of them. Untested, though :) – helenhousandi Aug 31 '11 at 20:45
  • Looks like it's still only getting tags that are connected to posts. Also, how would you sort them by name instead of number of contained posts? – Zach Shallbetter Aug 31 '11 at 22:04
  • get_tags() is supposed to return tags alphabetically: codex.wordpress.org/Function_Reference/get_tags . Do you have a plugin or code that could be interfering? The above really should work. – helenhousandi Aug 31 '11 at 22:19
  • You're right, I apologize. It was "Role Scoper" I'm working to figure out what could cause that. Thanks for the help. – Zach Shallbetter Aug 31 '11 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.