How to display the_tags() as plain text

the_tags by default is displaying as URL. I need to display it as plain text to insert inside HTML attribute.

<?php 
    $tag = the_tags('');
?>

<div class="image-portfolio" data-section="<?php echo $tag ?>">

4 Answers
4

I’m glad you figured it out, but below is a quick semantic alteration (swapping your use of $tag singular and $tags plural will help it read closer to what it is doing; functionally it is no different).

I also added cases for inside and outside the Loop, and a conditional so you don’t end up trying to foreach loop when there are no tags.

Commented:

//We are inside the Loop here. Other wise we must pass an ID to get_the_tags()

    //returns array of objects
    $tags = get_the_tags();

    //make sure we have some
    if ($tags) {

        //foreach entry in array of tags, access the tag object
        foreach( $tags as $tag ) {

           //echo the name field from the tag object 
           echo $tag->name;
        }
    }

Inside Loop

    $tags = get_the_tags();

    if ($tags) {

        foreach( $tags as $tag ) {

            echo $tag->name;
        }
    }

Outside Loop:

    $id = '10';

    $tags = get_the_tags( $id );

    if ($tags) {

        foreach( $tags as $tag ) {

            echo $tag->name;
        }
    }

Further

Inside the loop, get_the_tags() uses the current post id. Outside of the loop, you need to pass it an id.
Either way, it returns an array of WP_TERM objects for each term associated with the relevant post.

[0] => WP_Term Object
    (
        [term_id] => 
        [name] => 
        [slug] => 
        [term_group] => 
        [term_taxonomy_id] => 
        [taxonomy] => post_tag
        How to display the_tags() as plain text => 
        [parent] => 
        [count] => 
    )

You could access each value the same way as above, i.e.:

    $tags = get_the_tags(); 
    if ($tags) {
        foreach( $tags as $tag ) {

            echo $tag->term_id;
            echo $tag->name;
            echo $tag->slug;
            echo $tag->term_group;
            echo $tag->term_taxonomy_id;
            echo $tag->taxonomy;
            echo $tag->description;
            echo $tag->parent;
            echo $tag->count;
        }
    }

Leave a Comment