Forums

Help -- php code to get first tag into variable (2 posts)

  1. texasag90
    Member
    Posted 3 years ago #

    Hello;

    I am trying to get the text of the first tag into a php variable in a template so I can use it for something. I am trying to do this in single.php (Kubrick). Code looks like this:

    <?php
                $category = get_the_category();
                $tag = get_the_tags();
                echo $tag[0]->name;
    ?>

    That does not work (no echo -- nothing). But, $category works just fine when used in a similar way.

    I thought I might need to dereference the pointer, but I cannot find a combination that works (I am a php hacker, obviously, not a pro).

    Can anyone tell me what is wrong?

    Thanks,
    Mark

  2. Anonymous
    Unregistered
    Posted 3 years ago #

    <?php
    $tag = get_the_tags();
    if ($tag) {
    $tag = $tag[0]; echo $tag->name;
    }
    ?>

    That gets the information from the array of the first tag. Since its an Array it uses the -> selector to get the information. Category will work just fine because you are pulling it directly from the function.

    That code is pulled directly out of the Codex.

    http://codex.wordpress.org/Template_Tags/get_the_tags

    directly below the code on that page are the different variables you can call.

Topic Closed

This topic has been closed to new replies.

About this Topic