Override WordPress option value

Override WordPress option

Override WordPress option

Override WordPress option value temporally or conditionally? Did you ever have such desire? Is it possible? Yes!

Thanks to the WordPress core developers team it is not only possible but even simple. The only special thing you need to know is the WordPress option name.
In order to change some WordPress option value for the user, user role, date, time, post, etc. use proposed code snippet as the starting point. The code sample below automatically replaces global WordPress administrator email admin_email option value with own email of the current user with “Administrator” role. Just insert this code to your active theme functions.php file in order it starts working:

add_filter('pre_option_admin_email', 'override_admin_email');
function override_admin_email() {
    global $current_user; 
 
    if (!current_user_can('administrator')) {
        return false;
    }
    return $current_user->user_email;
}

WordPress adds special ‘pre_option_<option_name>’ filter for every option and applies it before return option value. Look at the get_option function wp-includes/option.php file:

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
	/**
	 * Filter the value of an existing option before it is retrieved.
	 *
	 * The dynamic portion of the hook name, $option, refers to the option name.
	 *
	 * Passing a truthy value to the filter will short-circuit retrieving
	 * the option value, returning the passed value instead.
	 *
	 * @since 1.5.0
	 *
	 * @param bool|mixed $pre_option Value to return instead of the option value.
	 *                               Default false to skip it.
	 */
	$pre = apply_filters( 'pre_option_' . $option, false );
	if ( false !== $pre )
		return $pre;

Using this filter we may override real value of any WordPress option with needed one according to our requirements.