Using the WooCommerce Settings API, how can I filter or add errors to settings values?

The WooCommerce Settings API documentation gives just enough information to get settings added to Gateway/Shipping Method screens.

However, unlike the native WordPress Settings API, there are no documented “sanitize” callbacks, like WordPress’ register_setting() has. Thus, if invalid content is supplied, I’m not sure where I’m supposed to be able to use add_settings_error or similar.

Read More

How am I supposed to do this, and what documentation did I overlook?

Related posts

Leave a Reply

1 comment

  1. Not sure where it’s documented (if at all) but I found an answer in code:

    woocommerce/classes/abstracts/abstract-wc-settings-api.php ~ 651 (in 2.0ish) has the following code:

    // Look for a validate_FIELDID_field method for special handling
    if ( method_exists( $this, 'validate_' . $k . '_field' ) ) {
        $field = $this->{'validate_' . $k . '_field'}( $k );
        $this->sanitized_fields[ $k ] = $field;
    

    Which means that if you added a setting with something like this:

    'username' => array(
        'title' => __( 'Username', 'woocommerce' ),
        'type' => 'text',
        'description' => __( 'Please enter your Payment Gateway Username; this is required for taking payments!', 'woocommerce' ),
        'default' => ''
    ),
    

    Then you’d need to add a method on the same payment gateway class called validate_username_field, that takes a single argument (the setting value; in this case the username) and returns the sanitized value and/or creates an error.

    E.g.,

    public function validate_username_field($value)
    {
        if (...)
        {
            // Valid username!
            return $value;
        } else {
            // Invalid? 
            add_settings_error(...); 
        }
    }
    

    Or something along those lines.