php - 如何在 woocomerce、wordpress 中隐藏条件函数的运输方式?
问题描述
我不知道如何在 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, 'product_cat', $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;
}
解决方案
推荐阅读
- php - 如何在 Codeigniter 4 中将数据插入到 2 个表中
- python - ValueError:无法将字符串转换为浮点数:Python 3D 图中的“2019-01-01 00:00:00”
- arrays - 在颤动中使用带有名称图像日期的数组列表的列表视图
- connection-pooling - 在 Heroku PostgreSQL 中使用 connect-pg-simple 尝试在没有 SSL 的情况下进行连接
- reactjs - 如何在前端存储socket.IO id?
- sql - 此表达式键入不正确,或者它太复杂而无法计算。SQL 访问
- typescript - 是否可以将 Set 的值用作类型或接口中的允许值?
- sql - 检查特定整数是偶数
- android - resConfigs 如何在 android (gradle) 中工作?
- sql - 使用触发器删除后更新表