2

In WooCommerce, I use the following code:

<?php
    global $product;
    $terms = get_the_terms( $product->get_id(), 'product_tag' );
    for ($i = 0; $i < count($terms); $i++) {
    $tags[] = $terms[$i]->slug;
    }
    ?>
<?php if ( $price_html = $product->get_price_html() ) : ?>
    <?php if (is_user_logged_in() && in_array('HIDDEN TAG', $tags)): ?>
        <span class="price">Please Log-in</span>
    <?php else: ?>
        <span class="price"><?php echo $price_html; ?></span>
    <?php endif; ?>
<?php endif; ?>

On products, this code should replace price by "Please Log-in" when customer is not logged on products that have 'HIDDEN TAG' product tag.

I don't understand why it doesn't work. Any help is appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

0

Your condition should be ! is_user_logged_in(). I have shorten and revisited your code:

<?php global $product;

// To be sure that we get the product Object (if needed)
if( ! is_a($product, 'WC_Product') )
    $product = wc_get_product( get_the_id() );

if ( $price_html = $product->get_price_html() ) { 
    // Get the term ID from 'HIDDEN TAG' product tag
    $term_id = get_term_by( 'name', 'HIDDEN TAG', 'product_tag' )->term_id;
    // added "!" to is_user_logged_in() for unlogged users and made some other changes
    if ( ! is_user_logged_in() && in_array( $term_id, $product->get_tag_ids() ) ) { 
        echo '<span class="price">'.__("Please Log-in").'</span>';
    } else {
        echo '<span class="price">'.$price_html.'</span>';
    } 
} ?>

It should work now.

The code could be even shorter, if you can set directly in the code the correct term ID for 'HIDDEN TAG' (instead of the term name), like for example (if 57 is the term Id) in:

in_array( 57, $product->get_tag_ids() )

Removing unneeded:

// Get the term ID from 'HIDDEN TAG' product tag
$term_id = get_term_by( 'name', 'HIDDEN TAG', 'product_tag' )->term_id;
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399