显示登录后的产品价格或特定产品的价格

时间:2017-02-06 19:27:58

标签: php wordpress woocommerce product price

我有一些代码阻止价格在所有产品上显示,如果用户没有登录。

我的问题是我有1个免费的产品,如果用户没有登录,我需要显示价格。

有人可以通过他的ID帮助我定位该单个产品并显示此特定价格,即使用户未登录也是如此。

这是我在 funcions.php 中的原始php代码,当用户未登录时阻止显示价格:

// Hide prices on public woocommerce (not logged in)
add_action('after_setup_theme','activate_filter') ; 
function activate_filter(){
    add_filter('woocommerce_get_price_html', 'show_price_logged');
}
function show_price_logged($price){
    if(is_user_logged_in()){
        return $price;
    }
    else
    {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
    return '<a href="' . get_permalink(woocommerce_get_page_id('myaccount')) . '">Call for pricing</a>';
    }
}

感谢。

1 个答案:

答案 0 :(得分:0)

清理了一下并将条件测试抽象为一个名为so_42075748_hide_price()的自定义函数,该函数测试用户是否登录测试产品的价格是否大于零。我还过滤了woocommerce_is_purchasable,使这些产品完全不适合那些可能知道您只需?add-to-cart=99将产品添加到购物车的人。

// Switch the Price HTML
add_filter('woocommerce_get_price_html', 'so_42075748_hide_price_logged', 10, 2 );
function so_42075748_hide_price_logged( $price, $product ){
    if( so_42075748_hide_price( $product ) ){
        // Not the ideal permalink in my opinion, but copying from original question.
        $price = '<a href="' . get_permalink( woocommerce_get_page_id( 'myaccount' ) ) . '">' . __( 'Call for pricing', 'your-textdomain' ) . '</a>';
    }
    return $price;
}

// Make products completely unpurchasable
add_filter( 'woocommerce_is_purchasable', 'so_42075748_is_purchasable', 10, 2 );
function so_42075748_is_purchasable( $purchasable, $product ){ 
    if( so_42075748_hide_price( $product ) ){
        $purchasable = false;
    }
    return $purchasable;
}

// Hide add to cart buttons
add_action( 'woocommerce_before_shop_loop_item', 'so_42075748_hide_prices' );
add_action( 'woocommerce_before_single_product', 'so_42075748_hide_prices' );
function so_42075748_hide_prices(){
    global $product; 

    if( so_42075748_hide_price( $product ) ){
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}

已编辑:进行了更完整的条件测试,同时测试价格是否为空。

// Your condition for hiding products
function so_42075748_hide_price( $product = null ){

    if( ! is_object( $product ) ){
        return true;
    }

    if( ! is_user_logged_in() ){

        $price = $product->get_price();

        if( ! is_null( $price ) && $price > 0 ){
            return true;
        }

    }

    return false;

}