I'm trying to add a custom settings tab to the WooCommerce settings screen. Basically I want to achieve similar functionality to the Product Settings tab via subsections/subtabs:
I haven't found any decent documentation on how to do this, but I've been able to add a custom tab using the following snippet:
class WC_Settings_Tab_Demo { public static function init() { add_filter( 'woocommerce_settings_tabs_array', __CLASS__ . '::add_settings_tab', 50 ); } public static function add_settings_tab( $settings_tabs ) { $settings_tabs['test'] = __( 'Settings Demo Tab', 'woocommerce-settings-tab-demo' ); return $settings_tabs; } } WC_Settings_Tab_Demo::init();
Based on what I've dug up from various threads/tutorials, I've been trying to add sections/subtabs into a new settings tab like this:
// creating a new sub tab in API settings add_filter( 'woocommerce_get_sections_test','add_subtab' ); function add_subtab( $sections ) { $sections['custom_settings'] = __( 'Custom Settings', 'woocommerce-custom-settings-tab' ); $sections['more_settings'] = __( 'More Settings', 'woocommerce-custom-settings-tab' ); return $sections; } // adding settings (HTML Form) add_filter( 'woocommerce_get_settings_test', 'add_subtab_settings', 10, 2 ); function add_subtab_settings( $settings, $current_section ) { // $current_section = (isset($_GET['section']) && !empty($_GET['section']))? $_GET['section']:''; if ( $current_section == 'custom_settings' ) { $custom_settings = array(); $custom_settings[] = array( 'name' => __( 'Custom Settings', 'text-domain' ), 'type' => 'title', 'desc' => __( 'The following options are used to ...', 'text-domain' ), 'id' => 'custom_settings' ); $custom_settings[] = array( 'name' => __( 'Field 1', 'text-domain' ), 'id' => 'field_one', 'type' => 'text', 'default' => get_option('field_one'), ); $custom_settings[] = array( 'type' => 'sectionend', 'id' => 'test-options' ); return $custom_settings; } else { // If not, return the standard settings return $settings; } }
I have been able to add new subsections to the Products tab using code similar to above, but it does not work with my new custom tab. Where did I go wrong?
1) To add a settings tab with sections you can first use the
woocommerce_settings_tabs_array
filter hook:2) To add new sections to the page, you can use the
woocommerce_sections_{$current_tab}
compound hook, where{$current_tab}
needs to be replaced with the Key slug set in a function:'; $array_keys = array_keys( $sections ); foreach ( $sections as $id => $label ) { echo '-
' . $label . ' ' . ( end( $array_keys ) == $id ? '' : '|' ) . '
';
}
echo '
'; } add_action( 'woocommerce_sections_my-custom-tab', 'action_woocommerce_sections_my_custom_tab', 10 );
3)In order to add settings and processing/saving, we will use a custom function and then call the function:
3.1) Add settings via
woocommerce_settings_{$current_tab}
composite hook:3.2) Handle/save settings via
woocommerce_settings_save_{$current_tab}
composite hook:result:
based on: