Bkkornaker
Bkkornaker

Reputation: 41

Cant get a basic "If Has Tag" Statement to work - Wordpress

I'm simply placing a small snippet of code on a woocommerce product page of my Wordpress website, to display an image "IF" the product has a specific TAG in place.

The code itself seems like it would be simple enough, and ive googled the heck out of this and tried many variations, with no luck on any of them.

<?php if( has_tag( 'tagnamehere') ) : ?> <div>my content</div> <?php endif; ?>

Also tried this:

<?php if( has_tag( 'tagnamehere' ) ){ echo '<div>my content</div>'; } ?>

Thats didnt work either.

basically, i just want it to look at the TAG of the product, and if the TAG exists, simply show the image (div). Nothing seems to work.

Upvotes: 4

Views: 789

Answers (1)

Xhynk
Xhynk

Reputation: 13890

WordPress actually uses what's called Taxonomies and Terms.

Taxonomies are basically a grouping of Posts or Custom Post Types (like 'Category' or 'Post Tag', and Terms are basically the individual grouping names 'Featured Posts', etc.

WooCommerce basically registers a Custom Post Type called product, and also a Taxonomy called product_tag. Note, this is different than the default Tags on Posts.

Effectively this means you'll need to check if the term 'tagnamehere' exists in the product_tag taxonomy, the easiest way would be with the has_term() function. This is basically like the "Custom Post Type with Custom Category (aka Taxonomy)" version of has_tag()

if( has_term( 'tagnamehere', 'product_tag' ) ){
    echo '<div>my content</div>';
}

Also to address your original "two versions" of code - The curly brace or alternative-syntax if statements work identically, and are mostly up to style/preference.

Upvotes: 3

Related Questions