用未登录用户的文本和特定产品标签替换WooCommerce产品价格

时间:2019-03-17 09:42:55

标签: php wordpress woocommerce product taxonomy-terms

在WooCommerce中,我使用以下代码:

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

在产品上,当客户未登录带有“ HIDDEN TAG”产品标签的产品时,该代码应用“请登录” 代替价格。

我不明白为什么它不起作用。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您的条件应该为! is_user_logged_in()。我已简化并重新考虑了您的代码:

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

现在应该可以工作。

  

代码可能会更短,如果您可以直接在代码中设置“ HIDDEN TAG” (而不是术语名称)的正确术语ID,例如例如(如果 57 是ID)

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

删除不必要的内容:

// Get the term ID from 'HIDDEN TAG' product tag
$term_id = get_term_by( 'name', 'HIDDEN TAG', 'product_tag' )->term_id;