php - 为给定顶级类别的所有子类别禁用特定的 WooCommerce 付款方式
问题描述
我正在尝试通过 WooCommerce 的给定类别 slug 为所有子类别停用 PayPal。目前,我的以下代码只是停用了一个类别的付款方式。是否可以为所有子类别停用?
<?php
/**
* Disable payment gateway based on category.
*/
function ace_disable_payment_gateway_category( $gateways ) {
// Categories that'll disable the payment gateway
$category_slugs = array( 'tobacco' );
$category_ids = get_terms( array( 'taxonomy' => 'product_cat', 'slug' => $category_slugs, 'fields' => 'ids' ) );
// Check each cart item for given category
foreach ( WC()->cart->get_cart() as $item ) {
$product = $item['data'];
if ( $product && array_intersect( $category_ids, $product->get_category_ids() ) ) {
unset( $gateways['ppec_paypal'] );
break;
}
}
return $gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'ace_disable_payment_gateway_category' );
解决方案
更新 2
要为顶级产品类别的子类别禁用特定支付网关,请使用以下命令:
add_filter( 'woocommerce_available_payment_gateways', 'disable_payment_gateway_subcategory' );
function disable_payment_gateway_subcategory( $payment_gateways ) {
if ( is_admin() ) return $payment_gateways; // Not on admin
$taxonomy = 'product_cat';
$term_slug = 'tobacco'; // Main top category
$term_id = get_term_by( 'slug', $term_slug, $taxonomy )->term_id; // get term Id
$children_ids = get_term_children( $term_id, $taxonomy ); // Get all children terms Ids
array_unshift( $children_ids, $term_id ); // Adding main term Id to the array
// Check each cart item for given subcategories of a top category
foreach ( WC()->cart->get_cart() as $cart_item ) {
$term_ids = wp_get_post_terms( $cart_item['product_id'], $taxonomy, array('fields' => 'ids') );
if ( array_intersect( $children_ids, $term_ids ) ) {
unset($payment_gateways['ppec_paypal']);
break; // stop the loop
}
}
return $payment_gateways;
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
推荐阅读
- python - 存储来自用户条目的多个输入
- java - AfterburnerFX 加载错误 找不到文件 xyz.fxml,尝试使用驼峰式大小写
- javascript - 如何使用 jQuery 重置克隆对象的值?
- node.js - 当我点击“heroku create”时,它不断显示另一个项目
- vue.js - vuetify 额外保证金
- r - r中25个变量之间的相关性
- python - Django Rest 框架和@staticmethod。它有什么好处?
- javascript - Express (Node) - 通过中间件循环发送错误消息的正确方法
- delphi - 如何在 Delphi 中知道 TForm 中的最大字幕长度
- angularjs - 如何在我的 angularjs 代码中解决这个错误