Advertisement
businessdad

WooCommerce - Filter payment methods based on custom field

May 17th, 2016
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.93 KB | None | 0 0
  1. /**
  2.  * WooCommerce customisation
  3.  * Filter the list of available payment gateways based on a custom
  4.  * field (in the example, "billing_customer_type").
  5.  *
  6.  * This customisation is compatible with the Aelia Currency Switcher
  7.  * (https://aelia.co/shop/currency-switcher-woocommerce/) and the other
  8.  * plugins developed by Aelia (https://aelia.co/shop/product-category/woocommerce/).
  9.  *
  10.  * @author Aelia <support@aelia.co>
  11.  * @link https://aelia.co
  12.  */
  13.  
  14.  
  15. /**
  16.  * Filters the availabel payment gateways based on the value of the
  17.  * "billing_customer_type" field.
  18.  *
  19.  * @param array gateways The array of gateways passed by WooCommerce.
  20.  * @return array The filtered array of gateways.
  21.  * @author Aelia <support@aelia.co>
  22.  * @link https://aelia.co
  23.  */
  24. add_filter('woocommerce_available_payment_gateways', function ($gateways) {
  25.     if(!empty($_POST['post_data'])) {
  26.         parse_str($_POST['post_data'], $post_data);
  27.  
  28.         $customer_type = strtolower(!empty($post_data['billing_customer_type']) ? $post_data['billing_customer_type'] : 'company');
  29.         switch($customer_type) {
  30.             case 'company':
  31.                 unset($gateways['paypal']);
  32.                 break;
  33.             case 'private':
  34.                 unset($gateways['cod']);
  35.                 break;
  36.         }
  37.     }
  38.  
  39.     return $gateways;
  40. }, 30);
  41.  
  42. /**
  43.  * Adds a script to ensure that, when the "customer type" field changes,
  44.  * the list of available payment gateways is updated.
  45.  * @author Aelia <support@aelia.co>
  46.  * @link https://aelia.co
  47.  */
  48. add_action('wp_footer', function() {
  49.   // The script is only needed on the checkout page
  50.   if(!is_checkout()) {
  51.     return;
  52.   }
  53.   ?>
  54.   <script type="text/javascript">
  55.     // When the "billing_customer_type" field changes,
  56.     // refresh the checkout data. This will update the
  57.     // list of payment gateways
  58.     jQuery(document).ready(function($) {
  59.       $('#billing_customer_type').on('change', function() {
  60.         $('#billing_country').change();
  61.       });
  62.     });
  63.   </script>
  64.   <?php
  65. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement