Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

1 Answer 1

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
add comment

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.