Verify if tag is used on posts

Try using the has_tag() conditional template tag. e.g., to query for the tag “foobar”:

<?php
if ( has_tag( 'foobar' ) ) {
    // The current post has the tag "foobar";
    // do something
} else {
    // The current post DOES NOT have the tag "foobar";
    // do something else
}
?>

If you’re inside the Loop, simply call <?php has_tag( $tag ); ?>; if you’re outside the Loop, you’ll need to pass the post ID: <?php has_tag( $tag, $post ); ?>

So, approximating your code:

$tags = get_tags( array( 'hide_empty' => false ) );
if ( $tags ) {
    foreach ( $tags as $tag ) {
        if ( has_tag( $tag->slug ) ) {
            // Current post has $tag;
            // output the tag link
            echo '<dt style="display:inline; float:left; padding-right:5px;"><strong><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . ' style="text-decoration:none;">' . $tag->name.'</a></strong></dt><dd style="margin-bottom:20px;">' . $tag->description . '</dd>';
        } else {
            // Current post does NOT have the tag;
            // output just the tag name
            echo $tag->name;
        }
    }
}

EDIT

So, another thought: if you’re pulling from an arbitrary list of terms, and you want to determine if that term is used as a post tag, then you can try using the term_exists() conditional; e.g. if you want to know if ‘foobar’ is used as a post tag:

<?php 
if ( term_exists( 'foobar', 'post_tag' ) ) {
    // The term 'foobar' is used as a post tag;
    // do something
}
?>

But I’m still confused about your source of “tags” here.

EDIT 2

So, now we will query based on the tag count being greater than zero (i.e., the tag has been used on at least one post):

    $tags = get_tags( array( 'hide_empty' => false ) );
    if ($tags) {
      foreach ($tags as $tag) {
        if ( 0 < $tag->count ) {
          echo '<dt style="display:inline; float:left; padding-right:5px;"><strong>';
              if ( has_tag( $tag->slug ) ) {
                echo '<a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . ' style="text-decoration:none;">' . $tag->name.'</a>';
              } else {
                echo $tag->name;
              }
          echo '</strong></dt><dd style="margin-bottom:20px;">' . $tag->description . '</dd>';
        }
      }
    }

Leave a Comment