WooCommerce Settings API
The WooCommerce Settings API provides a standardized way to add settings pages and fields to your extension. It handles form generation, validation, sanitization, and saving, allowing you to focus on your extension’s functionality.Overview
The Settings API is used throughout WooCommerce for:- Payment gateways
- Shipping methods
- Integration settings
- General WooCommerce settings pages
When to use the Settings API
Use the Settings API when you need to:- Add a settings page to the WooCommerce settings area
- Create settings for a payment gateway or shipping method
- Build an integration with external services
- Add configurable options to your extension
plugins/woocommerce/includes/abstracts/abstract-wc-settings-api.php.
Basic implementation
To use the Settings API, your class should extendWC_Settings_API.
Simple example
Here’s a basic example of a class using the Settings API:Form field types
The Settings API supports various field types. These are defined as constants inWC_Settings_Page:
Text input types
Textarea
Checkbox
Select dropdown
Multiselect
Section title and description
Complete settings page example
Here’s a comprehensive example showing how to create a full settings page:Adding settings to WooCommerce settings tabs
To add your settings to the main WooCommerce settings area, extendWC_Settings_Page instead:
Custom validation and sanitization
You can add custom validation for specific fields by creating avalidate_{field_id}_field method:
Getting and updating settings
Get a setting value
Update a setting value
Field attributes and options
Common field attributes:Best practices
Always use proper escaping and sanitization when working with settings data.
Security
- Sanitize input: Always sanitize user input before saving
- Validate data: Validate data types and formats
- Escape output: Always escape output when displaying
- Use nonces: Protect forms with WordPress nonces
Usability
- Use
desc_tip: Keep the interface clean by using tooltips for help text - Group related settings: Use sections to organize settings logically
- Provide defaults: Always set sensible default values
- Use placeholders: Help users understand expected input format
- Clear labels: Use descriptive titles and labels
Performance
- Cache settings: Don’t query options repeatedly
- Use transients: Cache expensive API calls
- Minimize autoloaded options: Don’t autoload large settings
Real-world example: Payment gateway settings
Here’s how payment gateways use the Settings API:Next steps
Now that you understand the Settings API:- Learn about WooCommerce hooks and filters
- Review extension development best practices
- Study the WooCommerce Settings API source code
- Explore existing payment gateway and shipping method implementations