我不知道如何获得在functions.php文件中创建和定义的全局变量。我在Wordpress中使用WooCommerce(3.7.1)。
我创建了一个名为 action_before_cart() 的函数,如果购物车中包含X个产品,则此函数会检查许多情况。在此函数中,我声明一个名为 $ shipping 的全局变量,使用该函数后的值应为: 0或1。
现在,根据$ shipping全局变量值,在hide_shipping_method_based_on_shipping_method函数中,在购物车或结帐期间将仅隐藏某些选定的运输方法。我通过在每个循环中通过unset($ rates [$ method_key_id]); 来取消每个方法来做到这一点。
因此,基本上我要做什么是在函数action_before_cart()中获取全局变量$ shipping,并在hide_shipping_method_based_on_shipping_method函数中使用它。
add_action('woocommerce_before_cart','action_before_cart');
function action_before_cart() {
$hasOfficePack = false;
$hasSundayCombo = false;
$officePack = array('office pack','77');
$sundayCombo = array('sunday combo','85');
// Loop through cart items if there's $officePack or $sundayCombo
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Check for $officePack category products in cart
if ( has_term( $officePack,'product_cat',$cart_item['product_id'] ) ) {
$hasOfficePack = true;
}
// Check for $sundayCombo category products in cart
if ( has_term( $sundayCombo,$cart_item['product_id'] ) ) {
$hasSundayCombo = true;
}
}
global $shipping; //the most important variable,which I want to be saved and used in the next function below
if ( $hasOfficePack ) {
$shipping = 0;
}
if ( $hasSundayCombo ) {
$shipping = 1;
}
}
add_filter( 'woocommerce_package_rates','hide_shipping_method_based_on_shipping_method',1,2 );
function hide_shipping_method_based_on_shipping_method( $rates,$package ) {
global $shipping; //the value of $shipping it's supposed to be set in the previous function
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ($shipping == 0) {
$method_key_ids = array('flat_rate:2','free_shipping:8','flat_rate:9');
} elseif($shipping == 1) {
$method_key_ids = array('flat_rate:2','flat_rate:9');
}
foreach( $method_key_ids as $method_key_id ){
unset($rates[$method_key_id]); // Remove the targeted methods
}
return $rates;
}