根据 URL 变量启用或禁用 WooCommerce 产品销售价格

Enable or disable WooCommerce products sale price based on URL variable

我正在尝试向使用以下 link www.example.com?sale and show regular prices to the rest of users. The code below does the job for single products, sale price is shown only to users with this 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 );

您需要将此 url 变量设置为 WC 会话,以避免在 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 文件。已测试并有效。