Add Custom Settings Tab to WooCommerce

This PHP code extends WooCommerce settings by adding a new ‘Exchange Rates’ tab with a custom number field for entering the exchange rate in any currency. It also includes functionality to save the entered value when the WooCommerce options are updated.

And here’s the result in WooCommerce > Settings :

Usage

get_option('exchange_rate_usd');

How The Code Works

  • Hook: add_action('woocommerce_settings_tabs_exchange_rates', 'add_exchange_rate_usd_field');
    This line adds an action hook to include a custom function (add_exchange_rate_usd_field) in the WooCommerce settings tabs under the ‘Exchange Rates’ tab.
  • Hook: add_action('woocommerce_admin_field_number', 'add_exchange_rate_usd_field');
    This line adds another action hook, specifying that the function add_exchange_rate_usd_field should be executed when a numeric field is rendered in the WooCommerce admin area.
  • Function: add_exchange_rate_usd_field()
    This function defines the content of the ‘Exchange Rates’ tab in WooCommerce settings. It uses the woocommerce_admin_fields function to define various form fields, including a title, a number field for the exchange rate in USD, and a section end.
  • Hook: add_action('woocommerce_update_options', 'save_exchange_rate_usd_field');
    This line adds an action hook to call the save_exchange_rate_usd_field function when the WooCommerce options are updated. This function will handle the saving of the entered exchange rate for USD.
  • Function: save_exchange_rate_usd_field()
    This function checks if the POST data contains the ‘exchange_rate_usd’ field and, if so, updates the WooCommerce option ‘exchange_rate_usd’ with the sanitized input.
  • Filter: add_filter('woocommerce_settings_tabs_array', function($settings_tabs) {...}, 50);
    This line adds a filter to modify the array of WooCommerce settings tabs. It injects a new tab called ‘Exchange Rates’ into the array, making it accessible in the WooCommerce settings menu.

Anonymous Function:

  • Appends the ‘Exchange Rates’ tab to the existing tabs array.
  • Returns the modified array.

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.