WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Using get_the_tag to label post titles (5 posts)

  1. AsraiLight
    Member
    Posted 5 years ago #

    I'm following the instructions on this page to add some HTML to my home page that labels a post title if it has one particular tag attributed to it. My code is placed in the template's index within the loop, after the title:

    <?php	// get the post's tags
    $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    echo $tag->name . ' ';
    }
    }
    ?>
    
    <?php  // If the post is tagged with "NSFW," add:
    if ($all_the_tags);
    $all_the_tags = get_the_tags();
    foreach($all_the_tags as $this_tag) {
    	if ($this_tag->name == "NSFW" ) {
    ?>
    <span class="nswf">[NSWF]</span>
    <?php 	} else {	// if it's not, do nothing
    	}
    }
    ?>

    However, I'm getting an error on the line with foreach($all_the_tags as $this_tag) { that it's an invalid argument.

    Any ideas?

  2. AsraiLight
    Member
    Posted 5 years ago #

    I've done some experimenting and it seems that whatever template tag I use (get_the_tags(), the_tags(), etc.) isn't grabbing the tags associated with that post for some reason. Why would it not be grabbing the tags?

    Someone please help? I am completely stumped here...

  3. AsraiLight
    Member
    Posted 5 years ago #

    Finally!!! It takes a lot of digging to get any answers around here, but this thread solved my problem. And just so anyone else who comes across this doesn't get frustrated that I didn't answer my own question:

    No, I didn't have start_wp() in my code, and I was using the_post() as I was supposed to, so that was not the problem. I had to add these two lines of code to my loop just before the "while" statement:

    global $wp_query;
    $wp_query->in_the_loop = true;

    And then this was the final code I used to add a message to my post titles if they were tagged with this particular tag:

    <?php
    $posttags = get_the_tags();	// get the post's tags
    if ($posttags) {
    foreach($posttags as $tag) {
    	if ($tag->name == 'NSFW') {	// If the post is tagged as "NSFW," add:
    ?>
    	<span class="nsfw">[NSFW]</span>
    <?php 	} else {	// if it's not, do nothing
    		}
    	}
    }
    ?>
  4. totalbigbrother
    Member
    Posted 4 years ago #

    Thank you so much AsraiLight.

    The tags was not showing up for me either, until i added the code before the while statement.

    Thanks very much!

  5. Mark / t31os
    Moderator
    Posted 4 years ago #

    You really should look at using has_tag, more efficient.

    http://codex.wordpress.org/Conditional_Tags#A_Tag_Page

    For use inside the normal loop, no need for any of that foreach loop above..

Topic Closed

This topic has been closed to new replies.

About this Topic