Woocommerce

How to Toggle WooCommerce Payments By Category for WordPress

This code allows you to enable or disable specific payment gateways for certain product categories in WooCommerce.

Steps and Functions

  • Plugin Setup

Create a new folder in the wp-content/plugins directory named woocommerce-toggle-payments-by-category. Inside this folder, create a PHP file named woocommerce-toggle-payments-by-category.php.

Explanation of Code

  • Plugin Header: The header contains the plugin’s name, description, version, author, and license information. This is required for WordPress to recognize the plugin.
  • Exit if accessed directly: This prevents direct access to the file for security purposes.
  • Class Definition: The main class WC_Toggle_Payments_By_Category encapsulates all the functionality.
  • Constructor: The constructor hooks into woocommerce_available_payment_gateways to filter available payment gateways and hooks into admin_menu and admin_init to create and manage the plugin settings page.
  • filter_payment_gateways Method: This method checks the product categories in the cart and disables payment gateways based on the settings. It retrieves the restricted gateways from the plugin’s options and removes them from the available gateways.
  • create_admin_menu Method: This method adds an options page under the Settings menu in the WordPress admin.
  • register_settings Method: This method registers the plugin’s settings.
  • settings_page Method: This method generates the settings page where the admin can configure which payment gateways to disable for each product category. It retrieves all product categories and payment gateways and displays them in a table format with checkboxes.

Usage

  • Activate the Plugin: Go to the WordPress admin, navigate to Plugins, and activate the “WooCommerce Toggle Payments By Category” plugin.
  • Configure Settings: Navigate to Settings -> Toggle Payments by Category, and configure which payment gateways to disable for each product category by checking the appropriate boxes.
  • Effect in Checkout: When a product from a category with restricted payment gateways is added to the cart, the restricted payment gateways will be removed from the available options at checkout.

    This code provides a flexible way to control payment gateways based on product categories, enhancing the WooCommerce store’s functionality.

Leave a Reply