• Resolved AsraiLight

    (@asrailight)


    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?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter AsraiLight

    (@asrailight)

    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…

    Thread Starter AsraiLight

    (@asrailight)

    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
    		}
    	}
    }
    ?>

    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!

    You really should look at using has_tag, more efficient.

    https://codex.www.ads-software.com/Conditional_Tags#A_Tag_Page

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

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Using get_the_tag to label post titles’ is closed to new replies.