WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This WordPress Codex document clearly shows how to get the name of the first tag of a post:

<?php
$posttags = get_the_tags();
$count=0;
if ($posttags) {
  foreach($posttags as $tag) {
    $count++;
    if (1 == $count) {
      echo $tag->name . ' ';
    }
  }
}
?>

How do I modify the aforementioned code, so that a hyperlink of the tag is shown, instead of just the name?

share|improve this question
up vote 3 down vote accepted

Instead of

echo $tag->name . ' ';

use

echo get_tag_link( $tag->term_id );

See the Codex on get_tag_link() and term_id.

And encapsulate the code in a function. Put this into your functions.php:

function wpse_49056_first_post_tag_link()
{
    if ( $posttags = get_the_tags() ) 
    {
        $tag = current( $posttags );
        printf(
            '<a href="%1$s" itemprop="url"><span itemprop="title">%2$s</span></a>',
            get_tag_link( $tag->term_id ),
            esc_html( $tag->name )
         );
    }
}

In your single.php you just call the function where you need the link:

<?php wpse_49056_first_post_tag_link(); ?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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