I check the sanity of some settings with sanitize_callback
. It works, but on fail, I want to reset the value do the default one. How can I do that?
$wp_customize->add_setting(
$attribute[0],
array(
"default" => $attribute[1],
"sanitize_callback" => $validate_func,
)
);
EDIT
An example for $validate_func
is kb_validate_url_facebook
which checks if the setting is an URL and if it contains facebook.com.
function kb_validate_url( $url, $valid, $default ) {
if ( $url === "" ) return $default;
$url = strtolower( esc_url_raw( $url ) );
if ( !strpos( $url, $valid ) ) {
if ( $url !== "" ) {
return null;
}
}
return $url;
}
function kb_validate_url_facebook( $url ) {
return kb_validate_url( $url, 'facebook.com', 'www.facebook.com/USERNAME' );
}
1 Answer
In the sanitize_callback
function you can look at the second argument which is the WP_Customize_Setting
instance and access the default
property there when returning due to an empty provided value:
add_action( 'customize_register', function( WP_Customize_Manager $wp_customize ) {
$wp_customize->add_setting( 'facebook_url', array(
'default' => 'https://www.facebook.com/USERNAME',
'sanitize_callback' => function( $url, $setting ) {
if ( empty( $url ) ) {
return $setting->default; // <===== Accessing default value.
}
$url = strtolower( esc_url_raw( $url ) );
$host = wp_parse_url( $url, PHP_URL_HOST );
if ( ! preg_match( '/^(www\.)?facebook\.com$/', $host ) ) {
return new WP_Error( 'invalid_url', __( 'Invalid URL or not one for Facebook', 'kb' ) );
}
return $url;
},
) );
} );