【问题标题】:echo Alert only once based on if statement PHP基于 if 语句 PHP 仅回显一次警报
【发布时间】:2016-01-14 20:31:41
【问题描述】:

此功能会在我的购物车中搜索特定产品,如果该产品存在,则删除运输服务。例如。如果产品 id:40 在购物车中,则禁用数组($shipping_services_to_hide)中的运输服务值。

我想向客户显示一条消息,通知他们运输限制,以警报的形式或最好将代码注入特定位置的购物车(基于类别 - 没有可用的 div id -。另外,使用 :before 或 :after 与 css content: 是可以接受的)(不知道这部分是否可以完成)

有什么好的方法可以做到这一点?

add_filter( 'woocommerce_package_rates','hide_shipping_method_if_particular_product_available_in_cart' , 10, 2 );

function hide_shipping_method_if_particular_product_available_in_cart( $available_shipping_methods ) {

global $woocommerce;

// products_array should be filled with all the products ids 
// for which shipping method (stamps) to be restricted.
$products_array = array( 
40
);

// You can find the shipping service codes by doing inspect element using 
// developer tools of chrome. Code for each shipping service can be obtained by 
// checking 'value' of shipping option.
$shipping_services_to_hide  = array( 
  'wf_shipping_ups:12',
  'wf_shipping_ups:02',
  'wf_shipping_ups:59',
  'wf_shipping_ups:01',
  'wf_shipping_ups:13',
  'wf_shipping_ups:14',
  'wf_shipping_ups:11',
  'wf_shipping_ups:07',
  'wf_shipping_ups:54',
  'wf_shipping_ups:08',
  'wf_shipping_ups:65'
  );

// Get all products from the cart.
$products = $woocommerce->cart->get_cart();

// Crawl through each items in the cart.
foreach ( $products as $key => $item ) {
    // If any product id from the array is present in the cart,
    // unset all shipping method services part of shipping_services_to_hide array. 
    if( in_array( $item['product_id'], $products_array ) ) { 
        foreach ( $shipping_services_to_hide as &$value ) {
            unset( $available_shipping_methods[ $value ] );

        }
        break;
    }
}

// return updated available_shipping_methods;
return $available_shipping_methods;
}

【问题讨论】:

    标签: php arrays if-statement foreach woocommerce


    【解决方案1】:

    您可以使用wc_add_notice()触发通知

    if( in_array( $item['product_id'], $products_array ) ) { 
        foreach ( $shipping_services_to_hide as &$value ) {
            unset( $available_shipping_methods[ $value ] );
            // add your notice here
            wc_add_notice( 'No shipping error.', 'your-plugin' ), 'notice' );
        }
        break;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-16
      • 2018-10-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多