I have a function that replaces the add to cart button and adds specific content on downloadable products. There are two type of downloadable products; 'Free Samples' and 'Activity Recipes'. These keywords are added as product tags and used to determine which is what when querying downloadable product. Which sounds simple enough, but my issues is that when you add more than one tag to a downloadable product, my code below is not picking up on the tag I need it to and then display the relevant code.
When printing the value of the variable $product_tag = null
, so this tells me something is wrong with $product_tag = get_term($tag)->name;
, but I cannot figure out what it needs to be or even if that is the issue.
So my question is how do I display specific content on downloadable products depending on if it has a specific tag in it's array of tags.
global $product;
if ( $product->is_downloadable('yes') ) {
if ( $product->get_price() > 0 ) {
do_action( 'woocommerce_' . $product->get_type() . '_add_to_cart' );
} else {
$downloads = $product->get_downloads();
$tags = $product->tag_ids;
foreach($tags as $tag) {
$product_tag = get_term($tag)->name;
}
foreach( $downloads as $key => $download ) {
if ($product_tag == 'Activity Recipes') {
echo '
<h4>Step 1</h4>
<a href="' . esc_url( $download['file'] ) . '" target="blank" >Download FREE template</a>
<hr />
<h4>Step 2 (Optional)</h4>
<p>Choose your products below as needed to help bring the activity to life:</p>
<a href="#details">Choose products</a>
';
} else if ($product_tag == 'Free Samples') {
echo '<p ><a href="' . esc_url( $download['file'] ) . '" target="blank" >Download FREE ' . $download['name'] . '</a></p>';
}
}
}
} else {
do_action( 'woocommerce_' . $product->get_type() . '_add_to_cart' );
}
CodePudding user response:
I'll elaborate a bit on CBroe's comment. Try replacing this:
foreach($tags as $tag) {
$product_tag = get_term($tag)->name;
}
with something like this:
$product_tags = [];
foreach($tags as $tag) {
$product_tags[] = get_term($tag)->name;
}
... and then replace your conditional if ($product_tag == 'Activity Recipes') {
with something like if in_array('Activity Recipes', $product_tags){
. You'd change the elseif
similarly.
That might theoretically work. (I obviously haven't tested it.) This of course assumes that your two conditional branches are mutually exclusive, and that you'll never have an item that has BOTH tags ('Activity Recipes' AND 'Free Samples'). If you run into that latter scenario, you might find that your logic is not behaving as you'd like it to.