2

我正在尝试向使用以下链接www.example.com?sale进入网站的用户显示销售价格,并向其他用户显示正常价格。下面的代码适用于单一产品,销售价格仅显示给具有此 URL www.example.com?sale的用户,但在汽车上它会切换回正常价格。并且仅适用于单一产品。我对 woocommerce 和 php 很陌生,希望有人可以帮我解决这个问题。非常感谢你的帮助!

function custom_wc_get_sale_price( $sale_price, $product ) {
    if (isset($_GET['sale'])) {
        return $sale_price;
} else {
        return $product->get_regular_price();
}

}
add_filter( 'woocommerce_product_get_sale_price', 'custom_wc_get_sale_price', 50, 2 );
add_filter( 'woocommerce_product_get_price', 'custom_wc_get_sale_price', 50, 2 );
4

1 回答 1

2

您需要将此 url 变量设置为 WC session 以避免在 Url 更改时丢失它:

// Early enable guest customer WC_Session
add_action( 'init', 'wc_session_enabler' );
function wc_session_enabler() {
    if ( is_user_logged_in() || is_admin() )
        return;

    if ( isset(WC()->session) && ! WC()->session->has_session() ) {
        WC()->session->set_customer_session_cookie( true );
    }
}

// Get "sale" url variable and set custom WC session variable
add_action( 'init', 'enable_sale_to_wc_session' );
function enable_sale_to_wc_session() {
    if ( isset($_GET['sale']) ) {
        WC()->session->set('has_sale', '1');
    }
}

// Enable sale price if it's set on products when 'sale' is as an URL variable
add_filter( 'woocommerce_product_get_price', 'enabling_sale_price', 1000, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'enabling_sale_price', 1000, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'enabling_sale_price', 1000, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'enabling_sale_price', 1000, 2 );
function enabling_sale_price( $price, $product ) {
    if ( isset($_GET['sale']) || WC()->session->get('has_sale') ) {
        return $price;
    } else {
        return $product->get_regular_price();
    }
}

// Remove custom WC session variable on thankyou page
add_action( 'woocommerce_thankyou', 'remove_enable_sale_from_wc_session' );
function remove_enable_sale_from_wc_session() {
    if ( WC()->session->get('has_sale') ) {
        WC()->session->__unset('has_sale');
    }
}

代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。

于 2020-10-14T20:04:20.863 回答